用camma将scala替换功能替换为“,”

时间:2018-08-21 08:44:00

标签: scala

下面的输入i必须在两个冒号(:)之间用“,”替换最后一个逗号(,)

println(input)
//[level:1,File:one,three,Flag:NA][level:1,File:two,Flag:NA]
println(input.replace(",", "\",\""))

得到的结果是:

//[level:1","File:one","three","Flag:NA][level:1","File:two","Flag:NA]

预期结果应该是

[level:1","File:one,three","Flag:NA][level:1","File:two","Flag:NA]

请帮助我。

1 个答案:

答案 0 :(得分:3)

val str1 = "[level:1,File:one,three,Flag:NA][level:1,File:two,Flag:NA]"

val regex1 = raw"(,)(\w+:)".r

val matches = regex1.findAllMatchIn(str1)

val str2 = matches.foldLeft(str1)({ case (str, m) =>
  str.replaceFirst(m.group(0), "\",\"" + m.group(2))
})
// str2: String = [level:1","File:one,three","Flag:NA][level:1","File:two","Flag:NA]