Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex Scala正则表达式匹配奇怪的行为_Regex_Scala - Fatal编程技术网

Regex Scala正则表达式匹配奇怪的行为

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

有人能解释一下为什么下面打印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("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!