模式匹配时是否可以使非捕获组在 Scala 正则表达式中工作 [英] Is it possible to make non-capturing groups work in scala regexes when pattern matching

查看:37
本文介绍了模式匹配时是否可以使非捕获组在 Scala 正则表达式中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我从文档中看到,非捕获组由 (:? ) 定义,就像在 Java 中一样.(我相信它是同一个底层库).

As far as I can see from the docs, non-capturing groups are defined by (:? ), as in Java. (I believe it's the same underlying library).

但是,这似乎不起作用:

However, this doesn't seem to work:

var R = "a(:?b)c".r
R.findFirstMatchIn("abc").get.group(1)

返回b"(当它应该为空时).我怀疑这通常不是问题,但是在进行模式匹配时,这意味着我现在不能这样做:

returns "b" (when it should be empty). I suspect this is not normally a problem, but when doing pattern matching, it means that I can't now do:

"abc" match {case R => println("ok");case _ => println("not ok")}
> not ok

我必须这样做:

"abc" match {case R(x) => println("ok");case _ => println("not ok")}
> ok

有什么办法可以使这项工作按预期"工作?

Is there any way to make this work "as expected"?

推荐答案

除了正确答案,使用 val 和 parens:

In addition to the correct answer, use val and parens:

scala> val R = "a(?:b)c".r  // use val
R: scala.util.matching.Regex = a(?:b)c

scala> "abc" match {case R() => println("ok");case _ => println("not ok")} // parens not optional
ok

您也可以始终使用通配符序列,而不必关心是否指定了捕获组.我最近发现了这个,发现它最清晰、最可靠.

You can also always use the wildcard sequence and not care whether you specified capturing groups. I discovered this recently and find it is most clear and robust.

scala> "abc" match {case R(_*) => println("ok");case _ => println("not ok")} 
ok

如果有任何匹配,_* 将会,包括一个返回 Some(null) 的提取器.

If anything matches, _* will, including an extractor returning Some(null).

这篇关于模式匹配时是否可以使非捕获组在 Scala 正则表达式中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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