Is it possible for non-capture groups to work in scala regex when pattern matching

As far as I can see from the documents, groups not related to capture are defined (:?), As in Java. (I believe this is the same base library).

However, this does not work:

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

returns "b" (when it should be empty). I suspect this is usually not a problem, but when performing pattern matching, this means that I cannot do it now:

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

I need to do:

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

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

+6
source share
2 answers

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 a sequence of wildcards and don't care if you specify capture groups. I discovered this recently and believe that it is the most clear and reliable.

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

If something matches, _* will be, including the extract, returning Some(null) .

+7
source

Your syntax seems to be wrong. It should be (? :).

http://docs.oracle.com/javase/tutorial/essential/regex/groups.html

Groups starting with (? Are pure, non-capturing groups that do not capture text and are not taken into account in the total amount of groups.

+3
source

Source: https://habr.com/ru/post/951678/


All Articles