ReplaceFirst () does not work when replaced with "$"

I do not understand why "$" 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 tag = "\\ $", then it works fine. But why do you have to run? thanks in advance.

+3
source share
3 answers

Because it is a special symbol of regular expressions (it collects groups in the results), but replaceFirstaccepts regex arguments. The documentation clearly warns you:

, () ($) , , ; . Matcher.replaceFirst(java.lang.String). Matcher.quoteReplacement(java.lang.String) , .

$. " ".
$g "g- ". a([a-z]+)([0-9]+) - $1 $2, . .

+6
0

$ matches the end of the line in the regular expression. Therefore, if you need it as a simple character, you need to avoid it. You can find more on JAVA Pattern

0
source

All Articles