我正在尝试遍历一个字符串并替换正则表达式匹配字符串的所有实例。出于某种原因,当我使用 if
时,它将起作用并仅替换正则表达式匹配的一个字符串实例。当我将 if
更改为 while
时,它会对自身进行一些奇怪的替换,并在第一个正则表达式匹配字符串上弄得一团糟,甚至没有触及其他字符串......
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();
}
最佳答案
除了系统输出,我只添加了最后一个任务。看看是否有帮助:
// 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);
}
关于java - 找到模式时替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13902323/