Loop through a string in lisp for alpha chars OR space
Asked Answered
C

3

7

I'm looking for how to loop through a string in LISP to check for alpha char or spaces. A sentence like "Coffee is Friend" is something that i want to check as Valid. But when i do (every #'alpha-char-p "coffee is best"') it fails on the spaces because the space is not technically alpha-char. Suggestions?

Thanks!

Cynar answered 17/4, 2016 at 19:32 Comment(0)
F
8

Simply test for alpha-char or space:

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

every takes as first parameter a function that must return non-nil on every element of the sequence second parameter.

Fructidor answered 17/4, 2016 at 19:40 Comment(0)
R
8

Using LOOP:

CL-USER > (loop for c across "tea is best"
                always (or (alpha-char-p c)
                           (char= c #\space)))
T
Rooke answered 17/4, 2016 at 20:50 Comment(0)
L
4

Depending on the complexity of the task, you might as well use regular expressions. If you load CL-PPCRE, you can write:

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

The regular expression that is accepted by the library is a Perl-like string, or a parse-tree. For example, calling (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 have to combine regular expressions, because it is much easier than concatenating and escaping strings.

Lockjaw answered 17/4, 2016 at 20:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.