为什么Scala正则表达式在模式匹配中的工作方式有所不同

xue*_*eng 1 regex scala pattern-matching

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

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

printlnemailRegex.pattern.matcher(email).matches())
Run Code Online (Sandbox Code Playgroud)

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

为什么会这样?

sep*_*p2k 6

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

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

printlnemailRegex.pattern.matcher(email).matches())
Run Code Online (Sandbox Code Playgroud)


Ben*_*tou 5

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

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"
})
Run Code Online (Sandbox Code Playgroud)

印刷品:

很酷,这是捕获的组:foo