Regex Scala正则表达式匹配奇怪的行为
有人能解释一下为什么下面打印5个匹配项吗Regex Scala正则表达式匹配奇怪的行为,regex,scala,Regex,Scala,有人能解释一下为什么下面打印5个匹配项吗 object RegExer extends App { val PATTERN = """([5])""".r print("5" match { case PATTERN(string) => string + " matches!" case _ => "No Match!" }) } 这个打印的不匹配 object RegExer extends App { val PATTERN = """[5]""".r print
object RegExer extends App {
val PATTERN = """([5])""".r
print("5" match {
case PATTERN(string) => string + " matches!"
case _ => "No Match!"
})
}
这个打印的不匹配代码>
object RegExer extends App {
val PATTERN = """[5]""".r
print("5" match {
case PATTERN(string) => string + " matches!"
case _ => "No Match!"
})
}
为什么没有括号,范围行为不起作用 在第二种情况下,您没有定义匹配的组。这就是正则表达式匹配中使用括号的目的:它们定义了应该捕获的内容(在本例中,稍后表示为变量)。您明确需要一个模式来返回单个组:模式(字符串)
string
这里是用于组(regex中的括号)
对于不带组的模式,应使用PATTERN()
:
"5" match {
case string @ PATTERN() => string + " matches!"
case _ => "No Match!"
}
// String = 5 matches!