Safe Replacement Strings With quoteReplacement

User-supplied replacement text containing $ or backslash throws in replaceAll; Matcher.quoteReplacement escapes both so substitution stays literal.

JavaSecurity Boundaries

Code

snippet
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

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:`.