Skip to content
Tutorials Center
My learning

Topics

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

Java Escaping, matches() and greedy matching

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.

Java Catastrophic backtracking, measured in steps

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 (\d is an illegal escape in a string literal). Text blocks follow the same rule.
  • String.matches anchors both ends. It never needs ^ and $; use Matcher.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+)+b is 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 a CharSequence that checks a deadline in charAt and 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. Pattern is thread-safe, Matcher is not. Do not keep a matcher in a static field.
  • Reading groups without a match. group() throws IllegalStateException unless find()/matches() returned true.
  • Unicode. \w, \d, \b are ASCII-only by default and case-insensitive matching ignores non-ASCII letters; use UNICODE_CHARACTER_CLASS or \p{L}. Also, . matches one code point, so an emoji with skin-tone modifier is two matches; use \X for a full grapheme.
  • Overusing regex. Parsing HTML, JSON, CSV with quotes or nested structures needs a parser. For simple tests startsWith, contains and split are clearer.
  • Recompiling in loops. Hoist Pattern.compile into a static final field.