如何在Scala中获得匹配的子组?

Cri*_* HG 7 python grouping scala

我在python中有以下内容:

  regex.sub(lambda t: t.group(1).replace(" ", "  ") + t.group(2),string)    
Run Code Online (Sandbox Code Playgroud)

其中regex是正则表达式,string是一个填充的字符串.

所以我试图在Scala中使用regex.replaceAllIn(...)函数而不是python 来做同样的事情sub.但是,我不知道如何获得匹配的子组.

group在Scala中有类似python函数的东西吗?

som*_*ytt 3

scaladoc 有一个例子。提供函数而Match不是字符串。

scala> val r = "a(b)(c)+".r
r: scala.util.matching.Regex = a(b)(c)+

scala> val s = "123 abcccc and abcc"
s: String = 123 abcccc and abcc

scala> r.replaceAllIn(s, m => s"a${m.group(1).toUpperCase}${m.group(2)*3}")
res0: String = 123 aBccc and aBccc
Run Code Online (Sandbox Code Playgroud)

生成的字符串也会进行组替换。

scala> val r = "a(b)(c+)".r
r: scala.util.matching.Regex = a(b)(c+)

scala> r.replaceAllIn(s, m => if (m.group(2).length > 3) "$1" else "$2")
res3: String = 123 b and cc

scala> r.replaceAllIn(s, m => s"$$${ if (m.group(2).length > 3) 1 else 2 }")
res4: String = 123 b and cc
Run Code Online (Sandbox Code Playgroud)