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.
Code
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
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 Pattern Quote Literal Regex Input print when run?
- Running the file directly is enough — expect labeled output lines such as `raw: compiled`, `raw:`, `quoted:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.