(发布,以防有人使用)。
我一直在寻找比OP更复杂的问题的解决方案-用递增的数字用相同的事物替换每次出现的事物
例如,替换如下内容:
<row id="1" />
<row id="2" />
<row id="1" />
<row id="3" />
<row id="1" />
这样:
<row id="2" />
<row id="3" />
<row id="2" />
<row id="4" />
<row id="2" />
无法在线找到解决方案,所以我用groovy编写了自己的脚本(有点难看,但能完成工作):
def replace_inc(String text, int startingIndex, String findTemplate) {
assert findTemplate.contains('_') : 'search template needs to contain "_" placeholder'
assert !(findTemplate.replaceFirst('_','').contains('_')) : 'only one "_" placeholder is allowed'
assert !text.contains('_____') : 'input text should not contain "______" (5 underscores)'
while (true) {
findString = findTemplate.replace("_",(startingIndex).toString())
if (!text.contains(findString)) break;
replaceString = findTemplate.replace("_", "_____"+(++startingIndex).toString())
text = text.replaceAll(findString, replaceString)
}
return text.replaceAll("_____","")
}
findTemplate = 'Row="_"'
path = /C:\TEMP\working_copy.txt/
startingIndex = 0
f = new File(path)
outText = replace_inc(f.text,startingIndex,findTemplate)
println "Results \n: " + outText
f.withWriter { out -> out.println outText }
println "Results written to $f"