Matcher replacement strings interpret dollar signs and backslashes, so quoteReplacement is required when a replacement comes from data.
Java Matcher.quoteReplacement: keep dollar signs and backslashes as data
Two languages meet at replaceAll
The search expression and replacement string have different parsing rules. Quoting the search token does not quote the replacement. A price label such as $47 can be read as a group reference and fail or produce the wrong text.
This fixture replaces a redacted amount in one ledger note. The first call shows the rejected raw replacement; the second keeps the exact supplied label. Pattern.quote handles the search side of the same boundary.
Do not use regex for a fixed literal replacement
When both sides are fixed strings and no matching rule is needed, String.replace uses literal character sequences and avoids these regex rules. Use a matcher only when the search criterion actually requires a pattern.
Working program
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LedgerLabelReplacement {
public static void main(String[] args) {
Matcher amount = Pattern.compile("REDACTED").matcher("settlement=REDACTED");
String suppliedLabel = "$47\\review";
try { System.out.println(amount.replaceAll(suppliedLabel)); }
catch (IndexOutOfBoundsException rejected) { System.out.println("raw replacement rejected"); }
System.out.println(amount.replaceAll(Matcher.quoteReplacement(suppliedLabel)));
}
}Output
raw replacement rejected
settlement=$47\reviewCost and ownership
replaceAll constructs a new string; replacement size grows with match count and supplied text length. Quote the replacement at the boundary, then apply an output-size limit if the input may contain many matches.
Common Mistakes
- Do not assume Pattern.quote affects replacement syntax.
- Do not interpolate a dollar-prefixed label as a group reference.
- Do not use replaceAll when literal String.replace expresses the rule.
Read next
Java Pattern.quote: match a supplied token literally, Java strings and content equality, regex matches find, Java StringBuilder: bounded text assembly.
