我正在尝试浏览字符串并替换正则表达式匹配字符串的所有实例。出于某种原因,当我使用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();
}
答案 0 :(得分:3)
除了sysouts我只添加了最后一个分配。看看它是否有帮助:
// 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);
}
答案 1 :(得分:0)
如果createRef(match)返回一个与(end-start)长度不同的字符串,那么您在docToProcess.substring(start,end)中使用的索引可能会重叠。
答案 2 :(得分:0)
不确定你到底遇到了什么问题但也许这个例子会有所帮助:
我想在句子中更改名称,如:
我们可以在Matcher
类
//this method can use Map<String,String>, or maybe even be replaced with Map.get(key)
static String getReplacement(String name) {
if ("Jack".equals(name))
return "Albert";
else if ("Albert".equals(name))
return "Paul";
else
return "Jack";
}
public static void main(String[] args) {
String sentence = "Jack and Albert are goint to see Paul. Jack is tall, " +
"Albert small and Paul is not in home.";
Matcher m = Pattern.compile("Jack|Albert|Paul").matcher(sentence);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, getReplacement(m.group()));
}
m.appendTail(sb);
System.out.println(sb);
}
输出:
Albert and Paul are goint to see Jack. Albert is tall, Paul small and Jack is not in home.