Scala 2.11(/ java8)匹配器不允许命名捕获组?

时间:2015-09-21 19:17:40

标签: regex scala

以下是一些使用命名组的scala匹配器代码:

  val regex=".*Completed (?<tstamp>[\d]{4}-[\d]{6})/(?<tname>[\w]+) (?<loops>[\d]+)Loops (?<cores>[\d]+)cores (?<mem>[\d]+)mb (?<inrecs>[\d]+)recs (?<nparts>[\d]+)parts (?<xform>[\w]+) (?<action>[\w]+) - duration=(?<duration>[\d]+\.[\d]+) seconds count=(?<outrecs>[\d]+).*"
  val rmatch = meta.regex.findFirstMatchIn(line)

输入是:

<03:54:26> Completed 0917-035231/CpuMem 100000000Loops 16cores 128mb 5000000recs 20parts GroupByKey Count - duration=41.408 seconds count=5000000

我们可以在Watch屏幕截图中看到第一个捕获组名为tstamp的模式(第三个条目)。它被正确捕获并可视为

 m[atch].group(1)

但是,在命名组

无法访问
m[atch].group("tstamp")

enter image description here

还有另一个SOF问题涉及这个主题但是已经五年了(在Java7出来之前支持命名组):Scala regex Named Capturing Groups

但是那个没有解决scala 2.11 / java8

的这种情况

2 个答案:

答案 0 :(得分:1)

Scala 2.12需要Java 8并且可以推进API。

同时,示例扩展名为:

https://github.com/som-snytt/regextractor/blob/master/core/src/test/scala/regex/GrTest.scala#L85

另一方面,https://github.com/travisbrown/expressier

答案 1 :(得分:1)

这是对som-snytt接受的答案的更多评论。他提到的扩展可以作为依赖直接包含在sbt中。 Maven需要更多的工作:通过包含以下jitpack git-to-maven工具:

Try jitpack, you just need to add the dependency, jitpack will build others for you.

来自Can I use a GitHub project directly in Maven?

From home page:

jitpack
Easy to use package repository for Gradle and Maven projects
JitPack builds GitHub projects on demand and provides ready-to-use packages
HOW

Add repository first
<repository>
    <id>jitpack.io</id>
    <url>https://jitpack.io</url>
</repository>
Add dependency
<dependency>
    <groupId>com.github.User</groupId>
    <artifactId>Repo name</artifactId>
    <version>Release tag</version>
</dependency>