Safe Replacement Strings With quoteReplacement
User-supplied replacement text containing $ or backslash throws in replaceAll; Matcher.quoteReplacement escapes both so substitution stays literal.
Code
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TemplateExpander {
public static void main(String[] args) {
// a username containing $: in a replacement string it would be parsed as a group reference
String hostile = "Mallory$1";
Pattern needle = Pattern.compile("guest");
String template = "hello guest, bye guest";
// a direct replaceAll hits $1 pointing at a nonexistent group and throws IllegalArgumentException
try {
needle.matcher(template).replaceAll(hostile);
} catch (IllegalArgumentException e) {
System.out.println("raw replaceAll threw: " + e.getClass().getSimpleName());
}
// quoteReplacement escapes $ and \ into literal text, so the replacement string is written verbatim
String safe = needle.matcher(template)
.replaceAll(Matcher.quoteReplacement(hostile));
System.out.println("safe: " + safe);
// the pattern itself needs the same protection: Pattern.quote strips * of its wildcard meaning
String wildcard = "g*st";
System.out.println("literal: " + Pattern.compile(Pattern.quote(wildcard))
.matcher("g*st").replaceAll("x"));
}
}How it works
Safe Replacement Strings With quoteReplacement keeps everything in the class TemplateExpander and the function main.
Using it
Running the file prints labeled results such as raw replaceAll threw:, safe:, literal: — each operation’s effect is visible in the output.
Key statements
.replaceAll(Matcher.quoteReplacement(hostile));
needle.matcher(template).replaceAll(hostile);
String template = "hello guest, bye guest";
Interactive Tools for This Topic
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
FAQ
- What does Safe Replacement Strings With quoteReplacement print when run?
- The script runs standalone; its 3 labeled outputs include `raw replaceAll threw:`, `safe:`, `literal:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.