Java Reference ยท Text, Formatting and Regex
Regex pitfalls
Common Java regex mistakes: double escaping, matches vs find, catastrophic backtracking and ReDoS, greedy quantifiers, shared Matchers, and Unicode surprises.
Regular expressions are compact and powerful, and most bugs with them come from a small set of repeating mistakes. Some give wrong results quietly (matching too much, too little or only part of the input); others make a program freeze or consume a CPU core for minutes on a short string. This page collects the traps that are specific to Java's java.util.regex and how to avoid each.
Treat it as a checklist when a regex misbehaves or before you accept patterns or inputs from outside your program.
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Pitfalls and fixes
- Double escaping. Write
"\\d","\\.","\\\\"in Java source. A single backslash before most letters is a compile error (\dis an illegal escape in a string literal). Text blocks follow the same rule. String.matchesanchors both ends. It never needs^and$; useMatcher.find()to look inside a string.- Unescaped meta-characters.
.,|,$,*,+,?,(,),[,{and\are special."a.b".split(".")returns an empty array; use"\\.". - User input in a pattern must pass through
Pattern.quote, otherwise it can break the pattern, change its meaning or become an injection vector. The same goes for replacement strings (Matcher.quoteReplacement). - Greedy vs lazy.
.*consumes as much as it can. Prefer a negated class ([^<]*) which is clearer and faster than.*?. - Catastrophic backtracking (ReDoS). Repeated or nested quantifiers over overlapping parts, such as
(.*a){8}or(a*)*, can need a very large number of steps when the match fails (exponential or high-degree polynomial). The second example shows the reads growing from about 1,500 to over a million as the input grows from 8 to 20 characters. Recent JDKs cache some nested-loop cases, so the textbook(a+)+bis milder than in older versions, but you should not count on that. Defenses: simplify the pattern, use possessive quantifiers (a++) or atomic groups ((?>...)), validate length before matching, avoid running untrusted patterns, and run risky matches with a time limit (for example by matching against aCharSequencethat checks a deadline incharAtand throws). - Java regex is backtracking, not linear time. There is no built-in timeout; modern JDKs optimize some cases but you cannot rely on it.
- Shared
Matcher.Patternis thread-safe,Matcheris not. Do not keep a matcher in a static field. - Reading groups without a match.
group()throwsIllegalStateExceptionunlessfind()/matches()returnedtrue. - Unicode.
\w,\d,\bare ASCII-only by default and case-insensitive matching ignores non-ASCII letters; useUNICODE_CHARACTER_CLASSor\p{L}. Also,.matches one code point, so an emoji with skin-tone modifier is two matches; use\Xfor a full grapheme. - Overusing regex. Parsing HTML, JSON, CSV with quotes or nested structures needs a parser. For simple tests
startsWith,containsandsplitare clearer. - Recompiling in loops. Hoist
Pattern.compileinto astatic finalfield.