Scala regex命名为捕获组 [英] Scala regex Named Capturing Groups
问题描述
在
In scala.util.matching.Regex trait MatchData I see that there support for groupnames , I thought that this was related to (Regex Named Capturing Groups)
但是由于据我所知,Java直到版本7才支持组名( ref ), Scala版本2.8.0(Java HotSpot(TM)64位服务器VM,Java 1.6。给了我这个例外:
But since Java does not support groupnames until version 7 as I understand it (ref), Scala version 2.8.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6. gives me this exception:
scala> val pattern = """(?<login>\w+) (?<id>\d+)""".r
java.util.regex.PatternSyntaxException: Look-behind group does not have an obvio
us maximum length near index 11
(?<login>\w+) (?<id>\d+)
^
at java.util.regex.Pattern.error(Pattern.java:1713)
at java.util.regex.Pattern.group0(Pattern.java:2488)
at java.util.regex.Pattern.sequence(Pattern.java:1806)
at java.util.regex.Pattern.expr(Pattern.java:1752)
at java.util.regex.Pattern.compile(Pattern.java:1460)
所以问题是Scala支持命名捕获组吗?如果有的话,那里有什么例子吗?
So the question is Named Capturing Groups supported in Scala? If so any examples out there?
推荐答案
恐怕Scala的命名组定义方式不同。只是原始模式中未命名(即刚刚编号)的组的后处理别名。
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.
这里有一个例子:
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"));
}
}
此打印(在ideone.com上看到):
Bond, James
这里发生的是在 Regex的构造函数中
,我们为组1、2等提供别名。然后我们可以使用这些名称来引用这些组。这些名称不是模式本身所固有的。
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 regex命名为捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!