scala - 使用正则表达式替换第 2 次和第 4 次出现 [英] scala - replace 2nd and 4th occurence using regex

查看:73
本文介绍了scala - 使用正则表达式替换第 2 次和第 4 次出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在下面的字符串中将 amt_2 和 amt_4 替换为 amt_ytd_2 和 amt_ytd_4.

I want to replace amt_2 and amt_4 to amt_ytd_2 and amt_ytd_4 in the below string.

scala> val a = "select amt_1, amt_2, amt_3, amt_4 from table"
a: String = select amt_1, amt_2, amt_3, amt_4 from table

scala> val reg = """(\d+)""".r
reg: scala.util.matching.Regex = (\d+)

我可以一次性替换所有这些,但是如何只替换字符串中出现的第 2 次和第 4 次?.

I'm able to replace all of them in one go, but how do I replace only the 2nd and 4th occurrence in the string?.

scala> reg.replaceAllIn(a, "_ytd_$1")
res23: String = select amt__ytd_1, amt__ytd_2, amt__ytd_3, amt__ytd_4 from table

scala>

我尝试过类似下面的方法,但没有得到预期的结果

I tried something like below, but not getting expected results

scala> var x = 0
x: Int = 0

scala> reg.replaceAllIn(a, {x+=1; if(x%2==0) "ytd" else " " })
res24: String = select amt_ , amt_ , amt_ , amt_  from table

scala>

推荐答案

您可以使用保护条件进行模式匹配.

You could pattern match with a guard condition.

"amt_(\\d+)".r.replaceAllIn(a, _ match {
    case m if m.group(1).toInt % 2 == 0 => s"amt__ytd_${m.group(1)}"
    case m                              => m.group(0)
  })
//res0: String = select amt_1, amt__ytd_2, amt_3, amt__ytd_4 from table

<小时>

更新

看来您想要第 2 次和第 4 次匹配,不一定是以 _2_4 结尾的匹配.试试这个.

It appears you want the 2nd and 4th match, not necessarily the matches ending with _2 and _4. Try this.

//string to modify
val a = "select amt_1, amt_2, amt_3, amt_4 from table"

//all the matches
val ms = "amt_(\\d+)".r.findAllMatchIn(a).toVector

//modify 2nd & 4th match (i.e. at index 1 & 3) if they exist
Vector(1,3).foldRight(a)(
  (x,s) => ms.lift(x).fold(s)(m => s.patch(m.start(1), "_ydt_", 0)))
//res0: String = select amt_1, amt__ydt_2, amt_3, amt__ydt_4 from table

请注意,这将修改索引为 3 的第 4 个匹配项,仅当找到那么多匹配项时.同样对于索引 1 处的第二个匹配项.因此,如果找到 0 或 1 个匹配项,则不会进行任何修改.如果找到 2 或 3 个匹配项,则仅生成 1 个 mod(在第 2 个匹配项中).

Notice that this will modify the 4th match, at index 3, only if that many were found. Likewise for the 2nd match at index 1. So if 0 or 1 matches are found, no mods are made. If 2 or 3 matches are found then only 1 mod is made (at the 2nd match).

这篇关于scala - 使用正则表达式替换第 2 次和第 4 次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆