I don’t understand why the “$” is special.
String str = "bla aa";
String tag = "$";
str = str.replaceFirst("aa", tag);
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
If I change the tag = “\\$”, then it works fine. But why does it need to be escaped? thanks in advance.
Because it is a special regex symbol (in results it’s about capturing groups), and
replaceFirsttakes regex arguments. The documentation explicitly warns you:Now a bit more about
$. In the regex pattern it means “end of line”.In the replacement string,
$gmeans “the g th group”. So for a regexa([a-z]+)([0-9]+), you have two groups –$1and$2, and you can refer to them when replacing. See the explanation here