简体   繁体   中英

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?

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")

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 az and hyphen - .

While re-find surely is an option, re-matches is what you'd want for matching a whole string without having to provide ^...$ wrappers:

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

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

So, your if-construct could look like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM