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

3
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"

}

我不明白。我尝试了所有在互联网上找到的替换方法,包括所有我能找到的Stack Overflow的方法。我甚至尝试了\u0024!出了什么问题?

2个回答

6

替换不是在原地进行的(Java中无法修改String,它们是不可变的),而是保存在一个新的String中,并由该方法返回。您需要保存返回的String引用才能发生任何事情,例如:

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

该死!我以前做过一百万次,而且是正确的方法。我只是忘了它!谢谢! - emha
4
如果您发现答案有用,为什么不接受它呢? - RAS

4

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接