Loop through a string in lisp for alpha characters OR space

I am looking for how to iterate over a string in LISP to check alpha char or spaces. A Coffee-Friend sentence is what I want to check as Valid. But when I do (each # 'alpha- char -p โ€œcoffee is the bestโ€), it fails in spaces because space is not technically alpha char. Suggestions?

Thanks!

+7
string lisp common-lisp space
source share
3 answers

A simple test for alpha- char or space:

(every (lambda (c) (or (alpha-char-p c) (char= c #\Space))) "coffee is best") 

every accepts as the first parameter a function that should return non-nil for each element of the second parameter of the sequence.

+8
source share

Using LOOP :

 CL-USER > (loop for c across "tea is best" always (or (alpha-char-p c) (char= c #\space))) T 
+8
source share

Depending on the complexity of the task, you can use regular expressions. If you download CL-PPCRE , you can write:

 (ppcre:scan "^[ a-zA-Z]*$" "Coffee is Friend") 

The regular expression accepted by the library is a Perl-like string or parsing tree. For example, a call (ppcre:parse-string "^[ a-zA-Z]*$") gives:

 (:SEQUENCE :START-ANCHOR (:GREEDY-REPETITION 0 NIL (:CHAR-CLASS #\ (:RANGE #\a #\z) (:RANGE #\A #\Z))) :END-ANCHOR) 

The above form has its uses when you need to combine regular expressions, because it is much simpler than concatenating and escaping strings.

+4
source share

All Articles