简体   繁体   English

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

[英]Pattern matching against regex strange behaviour scala

Can someone explain to me why is this happening, 有人可以向我解释为什么会这样,

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? 

I also tried: 我也尝试过:

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

You'll find the answer if you try to add a new option: 如果尝试添加新选项,则会找到答案:

"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")}

You are matching against a pattern without extract any value, the most common use of regex is, afaik, to extract pieces of the input string. 您要匹配一个不提取任何值的模式,正则表达式最常见的用法是afaik来提取输入字符串的片段。 So you should define at least one extraction by surrounding it with parenthesis: 因此,您应该通过用括号括起来来定义至少一个提取:

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

And then match against each of the extraction groups: 然后针对每个提取组进行匹配:

So this will return KO 所以这将返回KO

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

And this will return OK: 1 这将返回确定:1

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM