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函数的东西吗?
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)
归档时间: |
|
查看次数: |
243 次 |
最近记录: |