mo-seph
mo-seph

Reputation: 6223

Is it possible to make non-capturing groups work in scala regexes when pattern matching

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)

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

I have to do:

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

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

Upvotes: 8

Views: 4000

Answers (2)

som-snytt
som-snytt

Reputation: 39577

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

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

Upvotes: 9

Alejandro Pedraza
Alejandro Pedraza

Reputation: 537

It seems like you've got the syntax wrong. Should be (?:).

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

Groups beginning with (? are pure, non-capturing groups that do not capture text and do not count towards the group total.

Upvotes: 4

Related Questions