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"

}

I don't understand. I used all methods of doing the replacement I could find on the internets, including all stack overflow I could found. I even tried \u0024! What's wrong?

emha
  • 37
  • 2
  • 6

2 Answers2

6

The replacement isn't done inplace (A String can't be modified in Java, they are immutable), but is saved in a new String that is returned by the method. You need to save the returned String reference for anything to happen, eg:

template = template.replace("$B", "B");
Keppil
  • 45,603
  • 8
  • 97
  • 119
4

Strings are immutable. So you need to assign the return valur of replaceAll to a new String:

String s = template.replaceAll("\\$A", "A");
System.out.println(s);
Suraj Chandran
  • 24,433
  • 12
  • 63
  • 94