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

后端 未结 2 383
后悔当初
后悔当初 2021-01-18 01:38

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

2条回答
  •  无人及你
    2021-01-18 02:19

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

提交回复
热议问题