下面的输入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]
请帮助我。
答案 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]