Scala regex Named Capturing Groups

丶灬走出姿态 提交于 2019-11-29 03:19:05

I'm afraid that Scala's named groups aren't defined the same way. It's nothing but a post-processing alias to unnamed (i.e. just numbered) groups in the original pattern.

Here's an example:

import scala.util.matching.Regex

object Main {
   def main(args: Array[String]) {
      val pattern = new Regex("""(\w*) (\w*)""", "firstName", "lastName");
      val result = pattern.findFirstMatchIn("James Bond").get;
      println(result.group("lastName") + ", " + result.group("firstName"));
   }
}

This prints (as seen on ideone.com):

Bond, James

What happens here is that in the constructor for the Regex, we provide the aliases for group 1, 2, etc. Then we can refer to these groups by those names. These names are not intrinsic in the patterns themselves.

Scala does not have its own imlementation of regular expression matching. Instead the underlying regular expressions are Java's, so the details of writing patterns are those documented in java.util.regex.Pattern.

There you will find that the syntax you're using is actually that of the look-behind constraint, though according to the docs the < must be followed by either = (positive look-behind) or ! (negative look-behind).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!