【发布时间】:2014-11-27 07:41:17
【问题描述】:
我需要确保某个输入仅包含小写字母和连字符。实现这一目标的最佳惯用 clojure 是什么?
在 JavaScript 中我会这样做:
if (str.match(/^[a-z\-]+$/)) { ... }
clojure 中有什么更惯用的方式,或者如果是这样,正则表达式匹配的语法是什么?
【问题讨论】:
标签: regex string validation clojure
我需要确保某个输入仅包含小写字母和连字符。实现这一目标的最佳惯用 clojure 是什么?
在 JavaScript 中我会这样做:
if (str.match(/^[a-z\-]+$/)) { ... }
clojure 中有什么更惯用的方式,或者如果是这样,正则表达式匹配的语法是什么?
【问题讨论】:
标签: regex string validation clojure
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")
【讨论】:
re-matches 中进行了编辑,您还可以从提供给它的正则表达式中去除^...$。 :)
在这里使用 RegExp 很好。要将字符串与 clojure 中的 RegExp 匹配,您可以使用 build-in re-find function。
因此,您在 clojure 中的示例将如下所示:
(if (re-find #"^[a-z\-]+$" s)
:true
:false)
请注意,您的 RegExp 将仅匹配小拉丁字母 a-z 和连字符 -。
【讨论】:
虽然re-find 肯定是一个选项,但re-matches 是您想要匹配整个字符串而无需提供^...$ 包装器:
(re-matches #"[-a-z]+" "hello-there")
;; => "hello-there"
(re-matches #"[-a-z]+" "hello there")
;; => nil
因此,您的 if 构造可能如下所示:
(if (re-matches #"[-a-z]+" s)
(do-something-with s)
(do-something-else-with s))
【讨论】: