Pattern matching against regex strange behaviour scala

冷暖自知 提交于 2019-12-24 06:51:27

问题


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

回答1:


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. 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

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

And this will return OK: 1

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


来源:https://stackoverflow.com/questions/57660550/pattern-matching-against-regex-strange-behaviour-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!