(萬一有人發帖可能有一個使用它)。
我一直在尋找一個問題略高於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(醜了一點,但做這項工作):
/**
* <p> Finds words that matches template and increases them by 1.
* '_' in word template represents number.
*
* <p> E.g. if template equals 'Row="_"', then:
* ALL Row=0 will be replaced by Row="1"
* All Row=1 will be replaced by Row="2"
* <p> Warning - your find template might not work properly if _ is the last character of it
* etc.
* <p> Requirments:
* - Original text does not contain tepmlate string
* - Only numbers in non-disrupted sequence are incremented and replaced
* (i.e. from example below, if Row=4 exists in original text, but Row=3 not, than Row=4 will NOT be
* replaced by Row=5)
*/
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("_____","") // get rid of '_____' character
}
// input
findTemplate = 'Row="_"'
path = /C:\TEMP\working_copy.txt/
startingIndex = 0
// do stuff
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"
Notepad ++替代品不做數學,也不做正則表達式。 – Amber
如果有可能,這是非常困難的。在正則表達式中沒有數字概念(所以沒有+1),並且在匹配正則表達式時沒有簡單的方法來累積數據(所以沒有「下一個」匹配)。如果您真的需要自動執行此操作,XSLT可能會幫助您。 – 2011-09-29 20:12:41
@Amber Notepad ++具有有限的正則表達式功能。 – Karolis