Search code examples
javaregexstringreplacedollar-sign

Java replaceAll / replace string with instances of 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"

}

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?


Solution

  • 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");