找到模式时替换 [英] Replace While Pattern is Found
问题描述
我试图通过一个字符串,并替换正则表达式匹配字符串的所有实例。由于某些原因,当我使用 if
,那么它将工作,并替换一个正则表达式匹配的字符串实例。当我把 if
更改为,而
时,它会对自己进行一些奇怪的替换,并使第一个正则表达式匹配字符串,而不是甚至触及其他... ...
$ $ p $ $ $ $ $ $ $ pattern = Pattern.compile(regex);
matcher = pattern.matcher(docToProcess); $(matcher.find()){
start = matcher.start();
end = matcher.end();
match = docToProcess.substring(start,end);
stringBuilder.replace(start,end,createRef(match));
docToProcess = stringBuilder.toString();
}
添加了最后的作业。看看是否有帮助:
//你的代码片段:
pattern = Pattern.compile(regex);
matcher = pattern.matcher(docToProcess); $(matcher.find()){
start = matcher.start();
end = matcher.end();
match = docToProcess.substring(start,end);
String rep = createRef(match);
stringBuilder.replace(start,end,rep);
docToProcess = stringBuilder.toString();
// my addition:
System.out.println(Found:'+ matcher.group()+');
System.out.println(替换为:'+ rep +');
System.out.println( - >+ docToProcess);
matcher = pattern.matcher(docToProcess);
}
I'm trying to go through a string and replace all instances of a regex-matching string. For some reason when I use if
then it will work and replace just one string instance of a regex-match. When I change the if
to while
then it does some weird replacement over itself and makes a mess on the first regex-matching string while not even touching the others...
pattern = Pattern.compile(regex);
matcher = pattern.matcher(docToProcess);
while (matcher.find()) {
start = matcher.start();
end = matcher.end();
match = docToProcess.substring(start, end);
stringBuilder.replace(start, end, createRef(match));
docToProcess = stringBuilder.toString();
}
Aside from the sysouts I only added the last assignment. See if it helps:
// your snippet:
pattern = Pattern.compile(regex);
matcher = pattern.matcher(docToProcess);
while (matcher.find()) {
start = matcher.start();
end = matcher.end();
match = docToProcess.substring(start, end);
String rep = createRef(match);
stringBuilder.replace(start, end, rep);
docToProcess = stringBuilder.toString();
// my addition:
System.out.println("Found: '" + matcher.group() + "'");
System.out.println("Replacing with: '" + rep + "'");
System.out.println(" --> " + docToProcess);
matcher = pattern.matcher(docToProcess);
}
这篇关于找到模式时替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!