用唯一替换替换字符串中的所有实例

我试图用一个唯一的替换替换特定String的所有实例。

我想要的是什么:

如果我有这个字符串:

String testScript = "while(true) { } while (10 < 7) { } while((10 < 7)) { }"; 

我想要这个输出:

 while(arg0 < 5000 && true) { } while(arg1 < 5000 && 10 < 7) { } while(arg2 < 5000 && (10 < 7)) { } 

是)我有的:

但是,传递给replaceAll的字符串不会再次被查询(现在很明显我想到了它)。

 while(arg0 < 5000 && true) { } while(arg0 < 5000 && 10 < 7) { } while(arg0 < 5000 && (10 < 7)){ } 

任何答案或评论,一如既往,非常感谢。

SSCCE:

 public static void main(String[] args) { int counter = 0; String testScript = "while(true) { } while (10 < 7) { } while((10 < 7)) { }"; String out = testScript.replaceAll("while\\s*\\(", "while(arg" + (counter++) + " < 5000 && "); System.out.println(out); } 

您似乎正在从Matcher类中寻找appendReplacementappendTail方法。

这两种方法都需要临时缓冲区,其中将放置新的(替换)版本的字符串。 在这种情况下使用StringBuffer

它们的目的是添加缓冲区块的修改文本

  • appendReplacement(StringBuffer sb, String replacement)当匹配时将找到最后一次匹配的文本(或者在从字符串开始的第一次匹配的情况下)直到当前匹配+替换的开始
  • appendTail(StringBuffer sb)当没有匹配时,我们还需要在最后一次匹配后添加文本(或者如果没有匹配整个原始字符串)。

换句话说,如果你有文本xxxxfooxxxxxfooxxxx并且想要将foo替换为bar匹配,则需要调用

  xxxxfooxxxxxfooxxxx 1. appendReplacement ^^^^^^^ will add to buffer xxxxbar 1. appendReplacement ^^^^^^^^ will add to buffer xxxxxbar 3. appendTail ^^^^ will add to buffer xxxx 

所以在此缓冲区之后将包含xxxxbarxxxxxbarxxxx

演示

 String testScript = "while(true) { } while (10 < 7) { } while((10 < 7)) { }"; Pattern p = Pattern.compile("while\\s*\\("); Matcher m = p.matcher(testScript); int counter = 0; StringBuffer sb = new StringBuffer(); while(m.find()){ m.appendReplacement(sb, "while(arg"+ (counter++) + " < 5000 && "); } m.appendTail(sb); String result = sb.toString(); System.out.println(result); 

输出:

 while(arg0 < 5000 && true) { } while(arg1 < 5000 && 10 < 7) { } while(arg2 < 5000 && (10 < 7)) { }