【问题标题】:What is idiomatic clojure to validate that a string has only alphanumerics and hyphen?验证字符串是否只有字母数字和连字符的惯用 clojure 是什么?
【发布时间】:2014-11-27 07:41:17
【问题描述】:

我需要确保某个输入仅包含小写字母和连字符。实现这一目标的最佳惯用 clojure 是什么?

在 JavaScript 中我会这样做:

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

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

【问题讨论】:

    标签: regex string validation clojure


    【解决方案1】:
    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 中进行了编辑,您还可以从提供给它的正则表达式中去除^...$。 :)
    【解决方案2】:

    在这里使用 RegExp 很好。要将字符串与 clojure 中的 RegExp 匹配,您可以使用 build-in re-find function

    因此,您在 clojure 中的示例将如下所示:

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

    请注意,您的 RegExp 将仅匹配小拉丁字母 a-z 和连字符 -

    【讨论】:

      【解决方案3】:

      虽然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))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-28
        • 1970-01-01
        • 1970-01-01
        • 2015-08-22
        • 1970-01-01
        • 2015-06-10
        • 1970-01-01
        • 2017-11-02
        相关资源
        最近更新 更多