String's replaceAll() method and escape characters

When replacing characters using regular expressions, you're allowed to use backreferences, such as \1 to replace a using a grouping within the match.

This, however, means that the backslash is a special character, so if you actually want to use a backslash it needs to be escaped.

Which means it needs to actually be escaped twice when using it in a Java string. (First for the string parser, then for the regex parser.)


The javadoc of replaceAll says:

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.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.


If you don't need regex for replacing and just need to replace exact strings, escape regex control characters before replace

String trickyString = "$Ha!I'm tricky|.|";
String safeToUseInReplaceAllString = Pattern.quote(trickyString);

Tags:

Java

String

Regex