Raghuveer
Raghuveer

Reputation: 3057

Java String.replaceAll doesn't replace a dollar

I want to know why only $ is throwing java.lang.IllegalArgumentException: Illegal group reference exception and not any other special character :

public static void main(String[] args) {
    String s = "asdf ok done %test%";
    String as=s.replaceAll("%test%", "$dsf");
    System.out.println(as);
}

this can be overcome by a \\ added before the $ but why only for this character.

Upvotes: 1

Views: 1411

Answers (2)

Andy Turner
Andy Turner

Reputation: 140319

You can capture groups in the first parameter, and use them in the second parameter to mean "insert the bit you matched here":

String as = s.replaceAll("hello (.*) (\\d*)", "goodbye $2 $1");

When you use a $, the regex engine thinks you are trying to refer to such a group. Adding \\ escapes it, making it a literal dollar.

This is described in the Javadoc:

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.escapeReplacement(java.lang.String)to suppress the special meaning of these characters, if desired.)

Upvotes: 6

Anton Hlinisty
Anton Hlinisty

Reputation: 1469

You can find the answer in the Documentation

Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string;

See also

Upvotes: 1

Related Questions