【问题标题】:Why does Scala regexp work differently in pattern matching为什么 Scala 正则表达式在模式匹配中的工作方式不同
【发布时间】:2019-10-04 14:19:39
【问题描述】:

我有一个简单的正则表达式 val emailRegex = "\\w+@\\w+\\.\\w+".r 匹配简单的电子邮件(当然不是用于生产:)。当我运行以下代码时:

println(email match {
  case emailRegex(_) => "cool"
  case _ => "not cool"
})

printlnemailRegex.pattern.matcher(email).matches())

它打印not cooltrue。添加锚也无济于事:"^\\w+@\\w+\\.\\w+$".r 给出相同的结果。但是当我添加括号"(\\w+@\\w+\\.\\w+)".r 时,它会打印出cooltrue

为什么会这样?

【问题讨论】:

    标签: regex scala pattern-matching


    【解决方案1】:

    因为与正则表达式匹配的模式是关于捕获正则表达式组:

    val email = "foo@foo.com"
    val slightyDifferentEmailRegex = "(\\w+)@\\w+\\.\\w+".r // just add a group with two brackets
    println(email match {
      case slightyDifferentEmailRegex(g) => "cool" + s" and here's the captured group: $g"
      case _ => "not cool"
    })
    

    打印:

    很酷,这是捕获的组:foo

    【讨论】:

    • 不要犹豫,查看@sepp2k 答案,它有一种非常互补的方式来解释正在发生的事情。
    【解决方案2】:

    正则表达式模式的参数数量应与正则表达式中捕获组的数量相匹配。您的正则表达式没有任何捕获组,因此应该有零个参数:

    println(email match {
      case emailRegex() => "cool"
      case _ => "not cool"
    })
    
    printlnemailRegex.pattern.matcher(email).matches())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-01
      • 2019-11-01
      • 2014-06-06
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      相关资源
      最近更新 更多