针对正则表达式奇怪行为scala的模式匹配 [英] Pattern matching against regex strange behaviour scala

查看:71
本文介绍了针对正则表达式奇怪行为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? 

我也试过:

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

您正在匹配一个模式而不提取任何值,正则表达式最常见的用法是 afaik,用于提取输入字符串的片段.因此,您应该通过用括号将其括起来来定义至少一个提取:

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

然后匹配每个提取组:

所以这将返回 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

这篇关于针对正则表达式奇怪行为scala的模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆