使用正则表达式的Scala捕获组 [英] Scala capture group using regex
问题描述
假设我有以下代码:
val string = "one493two483three"
val pattern = """two(\d+)three""".r
pattern.findAllIn(string).foreach(println)
我希望 findAllIn
仅返回 483
,但是它返回的是 two483three
。我知道我可以使用 unapply
仅提取该部分,但是我必须为整个字符串设置一个模式,例如:
I expected findAllIn
to only return 483
, but instead, it returned two483three
. I know I could use unapply
to extract only that part, but I'd have to have a pattern for the entire string, something like:
val pattern = """one.*two(\d+)three""".r
val pattern(aMatch) = string
println(aMatch) // prints 483
还有另一种方法可以实现这一点,而无需使用直接来自 java.util
的类,并且不使用unapply?
Is there another way of achieving this, without using the classes from java.util
directly, and without using unapply?
推荐答案
以下是如何访问 group(1)
的示例每次比赛的结果:
Here's an example of how you can access group(1)
of each match:
val string = "one493two483three"
val pattern = """two(\d+)three""".r
pattern.findAllIn(string).matchData foreach {
m => println(m.group(1))
}
此打印 483
(在ideone.com上看到)。
根据模式的复杂性,您还可以使用环视功能仅匹配所需的部分。看起来像这样:
Depending on the complexity of the pattern, you can also use lookarounds to only match the portion you want. It'll look something like this:
val string = "one493two483three"
val pattern = """(?<=two)\d+(?=three)""".r
pattern.findAllIn(string).foreach(println)
上面的内容还会打印 483
((在ideone.com上看到)。
The above also prints "483"
(as seen on ideone.com).
- regular-expressions.info/Lookarounds
这篇关于使用正则表达式的Scala捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!