Java replaceAll / replace字符串与美元符号的实例

时间:2012-09-30 11:34:40

标签: java regex string replace dollar-sign

public static String template = "$A$B"

public static void somemethod() {
         template.replaceAll(Matcher.quoteReplacement("$")+"A", "A");
         template.replaceAll(Matcher.quoteReplacement("$")+"B", "B");
             //throws java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 3
         template.replaceAll("\\$A", "A");
         template.replaceAll("\\$B", "B");
             //the same behavior

         template.replace("$A", "A");
         template.replace("$B", "B");
             //template is still "$A$B"

}

我不明白。我使用了所有可以在互联网上进行替换的方法,包括我可以找到的所有堆栈溢出。我甚至试过了!怎么了?

2 个答案:

答案 0 :(得分:6)

替换不是在现场完成的(A String不能在Java中修改,它们是不可变的),但保存在新的String中由方法返回。您需要保存返回的String引用以确定发生的任何事情,例如:

template = template.replace("$B", "B");

答案 1 :(得分:4)

字符串是不可变的。因此,您需要将replaceAll的返回值分配给新的String:

String s = template.replaceAll("\\$A", "A");
System.out.println(s);