(Đăng trong trường hợp ai đó có thể sử dụng nó).
tôi đang tìm kiếm một giải pháp cho một vấn đề phức tạp hơn một chút so với OP - thay thế MỌI xảy ra một cái gì đó với số lượng bằng cách điều tương tự với tăng lên số
Ví dụ: Thay thế một cái gì đó như thế này:
<row id="1" />
<row id="2" />
<row id="1" />
<row id="3" />
<row id="1" />
Bằng cách này:
<row id="2" />
<row id="3" />
<row id="2" />
<row id="4" />
<row id="2" />
Couldnt tìm ra giải pháp trực tuyến vì vậy tôi đã viết kịch bản của riêng tôi trong groovy (một chút xấu xí nhưng không được công việc):
/**
* <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"
Thay thế Notepad ++ không làm toán, cũng không thực hiện regex. – Amber
Nếu có thể, nó vô cùng khó khăn. Không có khái niệm về các con số trong các biểu thức chính quy (do đó không có +1) và không có cách dễ dàng để tích lũy dữ liệu khi bạn so khớp với một regex (vì vậy không có kết quả "tiếp theo"). XSLT có thể giúp bạn ở đây, nếu bạn thực sự cần phải tự động hóa điều này. –
@Amber Notepad ++ có chức năng hạn chế regex. – Karolis