找到模式时替换

我正在尝试通过一个字符串并替换正则表达式匹配字符串的所有实例。 出于某种原因,当我使用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(); } 

除了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); } 

如果createRef(match)返回一个与(end-start)长度不同的字符串,那么您在docToProcess.substring(start,end)中使用的索引可能会重叠。

不确定你到底遇到了什么问题但也许这个例子会有所帮助:

我想在句子中更改名称,如:

  • 杰克 – >艾伯特
  • 艾伯特 – >保罗
  • 保罗 – >杰克

我们可以在Matcher类的appendReplacement和appendTail方法的帮助下完成这项工作

 //this method can use Map, 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.