Regex 什么是惯用clojure来验证字符串只有字母数字和连字符?

Regex 什么是惯用clojure来验证字符串只有字母数字和连字符?,regex,string,validation,clojure,Regex,String,Validation,Clojure,我需要确保某个输入只包含小写字母和连字符。要做到这一点,最好的习惯用语是什么 在JavaScript中,我会这样做: if (str.match(/^[a-z\-]+$/)) { ... } (if (re-matches #"[-a-z]+" s) (do-something-with s) (do-something-else-with s)) clojure中更惯用的方法是什么?如果是这样,正则表达式匹配的语法是什么?在这里使用正则表达式很好。要在clojure中将字符串与Re

我需要确保某个输入只包含小写字母和连字符。要做到这一点,最好的习惯用语是什么

在JavaScript中,我会这样做:

if (str.match(/^[a-z\-]+$/)) { ... }
(if (re-matches #"[-a-z]+" s)
  (do-something-with s)
  (do-something-else-with s))

clojure中更惯用的方法是什么?如果是这样,正则表达式匹配的语法是什么?

在这里使用正则表达式很好。要在clojure中将字符串与RegExp匹配,可以使用

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")
因此,您在clojure中的示例如下所示:

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

请注意,您的RegExp将只匹配较小的latyn字母
a-z
和连字符
-

,而
重新查找
肯定是一个选项,
重新匹配
是您在不必提供
^…$
包装器的情况下匹配整个字符串所需要的:

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

(re-matches #"[-a-z]+" "hello there")
;; => nil
因此,您的if构造可以如下所示:

if (str.match(/^[a-z\-]+$/)) { ... }
(if (re-matches #"[-a-z]+" s)
  (do-something-with s)
  (do-something-else-with s))

好的,既然您已经在
中编辑了重新匹配
,您还可以从提供给它的正则表达式中剥离
^…$
。)