Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is idiomatic clojure to validate that a string has only alphanumerics and hyphen?

I need to ensure that a certain input only contains lowercase alphas and hyphens. What's the best idiomatic clojure to accomplish that?

In JavaScript I would do something like this:

if (str.match(/^[a-z\-]+$/)) { ... }

What's a more idiomatic way in clojure, or if this is it, what's the syntax for regex matching?

like image 534
Sir Robert Avatar asked Nov 27 '14 07:11

Sir Robert


2 Answers

user> (re-matches #"^[a-z\-]+$" "abc-def")
"abc-def"
user> (re-matches #"^[a-z\-]+$" "abc-def!!!!")
nil
user> (if (re-find #"^[a-z\-]+$" "abc-def")
        :found)
:found
user> (re-find #"^[a-zA-Z]+" "abc.!@#@#@123")
"abc"
user> (re-seq #"^[a-zA-Z]+" "abc.!@#@#@123")
("abc")
user> (re-find #"\w+" "0123!#@#@#ABCD")
"0123"
user> (re-seq #"\w+" "0123!#@#@#ABCD")
("0123" "ABCD")
like image 54
runexec Avatar answered Sep 18 '22 09:09

runexec


Using RegExp is fine here. To match a string with RegExp in clojure you may use build-in re-find function.

So, your example in clojure will look like:

(if (re-find #"^[a-z\-]+$" s)
    :true
    :false)

Note that your RegExp will match only small latyn letters a-z and hyphen -.

like image 27
Leonid Beschastny Avatar answered Sep 17 '22 09:09

Leonid Beschastny