Reputation: 3057
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
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; seeMatcher.replaceAll
. UseMatcher.escapeReplacement(java.lang.String)
to suppress the special meaning of these characters, if desired.)
Upvotes: 6
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