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_Pattern Matching - Fatal编程技术网

Regex 针对正则表达式奇怪行为scala的模式匹配

Regex 针对正则表达式奇怪行为scala的模式匹配,regex,scala,pattern-matching,Regex,Scala,Pattern Matching,谁能给我解释一下为什么会这样 val p = """[0-1]""".r "1" match { case p => print("ok")} //returns ok, Good result "4dd" match { case p => print("ok")} //returns ok, but why? 我还尝试: "14dd" match { case p => print("ok") case _ => print("non")} //return

谁能给我解释一下为什么会这样

val p = """[0-1]""".r

"1" match { case p => print("ok")} 
//returns ok, Good result

"4dd" match { case p => print("ok")}
//returns ok, but why? 
我还尝试:

"14dd" match { case p => print("ok") case _ => print("non")}
//returns ok with: warning: unreachable code

如果尝试添加新选项,您将找到答案:

"4dd" match {
case p => print("ok")
 case _ => print("ko")
}

<console>:24: warning: patterns after a variable pattern cannot match (SLS 8.1.1)
 "4dd" match { case p => print("ok"); case _ => print("ko")}
然后与每个提取组进行匹配:

因此这将返回KO

scala> "4dd" match {
     |     case p(item) => print("ok: " + item)
     |      case _ => print("ko")
     |     }
ko
这将返回OK:1

scala>  "1" match {
     |         case p(item) => print("ok: " + item)
     |          case _ => print("ko")
     |         }
ok: 1

item是什么?item表示输入字符串的匹配部分(在您的示例中是整个字符串)。但是,假设您可以在整数和小数部分之间拆分一个数字,您的正则表达式将如下所示:“([0-1])\([0-1])\”,大小写为p(整数,小数)。非常感谢您的回答和解释!
scala>  "1" match {
     |         case p(item) => print("ok: " + item)
     |          case _ => print("ko")
     |         }
ok: 1