What is idiomatic clojure to verify that a string has only alphanumeric characters and hyphens?

I need to make sure that the specific input contains only lowercase letters and hyphens. What is the best idiomatic clojure for this?

In JavaScript, I would do something like this:

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

What is the more idiomatic way in clojure, or if so, what is the syntax for matching regular expressions?

+4
source share
3 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")
+4
source

Using RegExp here is great. To map a string to RegExp in clojure, you can use the built-in re-findfunction .

, clojure :

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

, RegExp a-z hyphen -.

+1

While re-findcertainly an option, re-matchesthis is what you would like to match an entire string without providing wrappers ^...$:

(re-matches #"[-a-z]+" "hello-there")
;; => "hello-there"

(re-matches #"[-a-z]+" "hello there")
;; => nil

So your if-construct might look like this:

(if (re-matches #"[-a-z]+" s)
  (do-something-with s)
  (do-something-else-with s))
+1
source

All Articles