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?

0

2 Answers 2

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");
Sign up to request clarification or add additional context in comments.

2 Comments

DAMN! I did it like a milion times before in the correct way. I just forgot it! Thanks!
@emha If you find the answer useful, why don't you accept it?
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.