【问题标题】:Why doesnt work regex为什么正则表达式不起作用
【发布时间】:2015-04-13 01:43:01
【问题描述】:

代码示例

14> case re:run("5162754", "/^\d+$/") of {match, _} -> ok end.
** exception error: no case clause matching nomatch  
15> case re:run(<<"5162754">>, "/^\d+$/") of {match, _} -> ok end.
** exception error: no case clause matching nomatch

为什么不匹配?

【问题讨论】:

    标签: regex erlang pattern-matching


    【解决方案1】:

    两件事:

    1. 您传递给re:run 的正则表达式不应被/ 包围。在其他语言中,您在 / 符号内编写正则表达式,但在 Erlang 中,正则表达式始终写为字符串,因此不需要 / 符号。

    2. 在 Erlang 字符串中,\d 表示“删除”字符(代码 127)。你在你的正则表达式中真正想要的是一个反斜杠,后跟字母d。为此,您需要使用另一个反斜杠来转义反斜杠:

      > re:run("5162754", "^\\d+$").
      {match,[{0,7}]}
      

    【讨论】:

      【解决方案2】:

      尝试使用 [0-9] 也可以,反斜杠没有问题

      re:run("5162754", "^[0-9]+$").
      

      【讨论】:

        猜你喜欢
        • 2014-06-01
        • 1970-01-01
        • 2013-12-05
        • 2012-11-17
        • 2014-12-03
        相关资源
        最近更新 更多