python - 如何在 Scala 中获取匹配项的子组?

标签 python scala grouping

我在 python 中有以下内容:

  regex.sub(lambda t: t.group(1).replace(" ", "  ") + t.group(2),string)    

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

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

Scala中有没有类似于python函数group的东西?

最佳答案

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

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

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

关于python - 如何在 Scala 中获取匹配项的子组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39860158/

相关文章:

python - 为什么 [].append(1) 是 None

scala - 在斯卡拉清除 map

scala - Sbt 依赖运行测试

python - 如何在 ZPT 中循环 OrderedDict 的子组?

python - Vim 作为 Mac OSX 上的 Python IDE

python - 绘制项目时出错 <pyqtgraph.opengl.items.GLScatterPlotItem.GLScatterPlotItem object at 0x0000026EB461B4C0>

python - 如何为脚本禁用 App Transport Security?

scala - 了解 Spark 监控 UI

python - pandas - 基于两列值的分组

matlab - 按 2 个变量分组,一个变量具有独特的颜色,另一个变量具有独特的形状