Pattern Quote Literal Regex Input

Wrap untrusted strings with Pattern.quote before compiling so regex metacharacters match literally instead of throwing or widening the match.

JavaSecurity Boundaries

Code

javasnippet
21 lines
import java.util.regex.Pattern;

public class LiteralSearch {

    public static void main(String[] args) {
        String userInput = "a.c*(";
        String haystack = "price a.c*( note";

        // 未加保护:输入被当作正则解释,未闭合的括号直接抛 PatternSyntaxException
        try {
            Pattern.compile(userInput).matcher(haystack).find();
            System.out.println("raw:     compiled");
        } catch (IllegalArgumentException e) {
            System.out.println("raw:     " + e.getClass().getSimpleName());
        }

        // Pattern.quote 用 \Q...\E 包住整串:元字符全部按字面量匹配
        Pattern literal = Pattern.compile(Pattern.quote(userInput));
        System.out.println("quoted:  " + literal.matcher(haystack).find());
    }
}

How the snippet works

One way to read it: the class LiteralSearch and the function main, doing all the work.

Applying it

Running the file prints labeled results such as raw: compiled, raw:, quoted: — each operation’s effect is visible in the output.

Statements that matter

Pattern literal = Pattern.compile(Pattern.quote(userInput));
Pattern.compile(userInput).matcher(haystack).find();

Interactive Tools for This Topic

FAQ

What does Pattern Quote Literal Regex Input print when run?
Running the file directly is enough — expect labeled output lines such as `raw: compiled`, `raw:`, `quoted:`.