Regex tester · Guide
Test Regex Java: Patterns, Flags and Escaping in Java
Java regex syntax is standard; Java string literals are not. Almost every discrepancy between a pattern that works in a tester and one that fails in Java comes down to backslashes or to `matches()` behaving differently than expected.
Every backslash doubles
Java has no raw string syntax for regex, so each backslash in the pattern needs escaping in the literal. \d+ in a tester becomes "\\d+" in Java source:
Pattern p = Pattern.compile("\\d{4}-\\d{2}-\\d{2}"); // matches 2026-08-29Java 15 text blocks help: inside """...""" you still escape, but multi-line patterns become readable. This doubling is the single most common cause of a pattern that compiled fine and matches nothing.
matches, find and lookingAt
matches() requires the entire string to match — it is an implicit anchor at both ends. find() searches for a match anywhere. lookingAt() anchors only at the start.
Most testers show find() behaviour by default, so a pattern that highlights matches in a tester can return false from matches():
Matcher m = Pattern.compile("\\d+").matcher("abc 123");
m.matches(); // false — the whole string is not digits
m.find(); // true — finds "123"Flags
Java passes flags to Pattern.compile as constants, or inline in the pattern:
Pattern.compile("abc", Pattern.CASE_INSENSITIVE); // (?i)
Pattern.compile(".+", Pattern.DOTALL); // (?s) — dot matches newline
Pattern.compile("^x", Pattern.MULTILINE); // (?m) — ^ and $ per line
Pattern.compile("a b", Pattern.COMMENTS); // (?x) — ignore whitespaceCASE_INSENSITIVE only covers ASCII unless you add UNICODE_CASE. For non-English text combine them, or matches on accented characters will surprise you.
Groups and performance
Named groups use (?<name>...) and are read with m.group("name"). Replacement strings use $1 or ${name}, and a literal $ in a replacement must be escaped with Matcher.quoteReplacement.
Compile patterns once and reuse them — String.matches() recompiles on every call, which is fine occasionally and expensive in a loop. Java also has no built-in backtracking limit, so a catastrophic pattern hangs the thread; prefer possessive quantifiers (.*+) or negated character classes for untrusted input.
Frequently asked questions
Why does my Java pattern match nothing?
Backslashes are usually the cause — each one must be doubled in a string literal.
Why does matches() return false when the tester shows a match?
matches() requires the whole string to match. Use find() for a search.
Should I compile patterns?
Yes, for anything reused. Pattern.compile once and store it; String.matches recompiles each call.
Ready to try it?
Open the free browser-based Regex tester and apply what you just read — no sign-up, runs locally.
Open the Regex tester tool