通过正则表达式模式查找索引位置并将它们替换为 Scala 中的索引列表

Find index locations by regex pattern and replace them with a list of indexes in Scala

我有这种格式的字符串: object[i].base.base_x[i],我得到了 List(0,1) 这样的列表。 我想在 scala 中使用正则表达式在给定字符串中找到匹配项 [i] 并将第一次出现替换为 0,将第二次出现替换为 1。因此得到类似 object[0].base.base_x[1].

的内容

我有以下代码:

val stringWithoutIndex = "object[i].base.base_x[i]"     // basically this string is generated dynamically
val indexReplacePattern = raw"\[i\]".r
val indexValues = List(0,1)     // list generated dynamically

if(indexValues.nonEmpty){ 
    indexValues.map(row => {
       indexReplacePattern.replaceFirstIn(stringWithoutIndex ,  "[" + row + "]")
     }) 
else stringWithoutIndex

由于 String 是不可变的,我无法更新 stringWithoutIndex 导致输出像 List("object[0].base.base_x[i]", "object[1].base.base_x[i]").

我尝试查看 StringBuilder,但不确定如何更新它。另外,有没有更好的方法来做到这一点?也欢迎提出除正则表达式以外的建议。

这个怎么样:

scala> val str = "object[i].base.base_x[i]" 
str: String = object[i].base.base_x[i]

scala> str.replace('i', '0').replace("base_x[0]", "base_x[1]")
res0: String = object[0].base.base_x[1]

这听起来像是 foldLeft 的工作。不需要 if (indexValues.nonEmpty) 检查。

indexValues.foldLeft(stringWithoutIndex) { (s, row) =>
  indexReplacePattern.replaceFirstIn(s, "[" + row + "]")
}

您可以使用 foldLeft 遍历 indexValues 中的整数并将字符串 stringWithoutIndex 作为起始值传递。

然后使用 replaceFirst 将第一个匹配项替换为 indexValues 的当前值。

如果你想使用正则表达式,你可以使用一个正 lookahead (?=]) 和一个正后向 (?<=\[) 来断言 i 在开盘和正方形之间括号。

(?<=\[)i(?=])

例如:

val strRegex = """(?<=\[)i(?=])"""
val res = indexValues.foldLeft(stringWithoutIndex) { (s, row) =>
  s.replaceFirst(strRegex, row.toString)
}

regex demo | Scala demo