Lesson · Regular Expressions
Regular expressions: Pattern, Matcher and the traps
15 min readRegular Expressions
A compiled pattern plus a matcher over each string: that is the whole API. The skill is reading a pattern as three questions (what counts, how often, where) and knowing the greedy, escaping and backtracking traps.
Compile once, match many
Pattern.compile turns a regex string into a reusable object; the matcher runs it against one input. String.matches compiles a throwaway pattern on every call, which is fine in a one-off check and wasteful in a loop.
matches demands the whole string; find scans for the next match anywhere and is driven in a while loop. That single difference explains most 'my regex works on regex101 but not in Java' moments: tools default to a search, matches defaults to an anchor.
Pattern zip = Pattern.compile("\\d{5}"); // compiled once (in Java source, \d is written \\d) zip.matcher("10115").matches(); // true, whole string is five digits Matcher m = zip.matcher("10115 and 80331"); while (m.find()) { ... } // 10115, then 80331
The grammar in one table
Every pattern answers three questions: what characters count, how many of them, and where in the string. Groups add structure, so results can be read back piece by piece.
| Piece | Means | Example |
|---|---|---|
| \d \w \s | digit, word char, whitespace | \d{4} matches 2026 |
| [aeiou] [^abc] | one of, none of | [A-Z][a-z]+ matches Name |
| . * + ? | any, zero+, one+, optional | colou?r matches color and colour |
| {2,4} {3,} {2} | counts | \d{2,4} matches 12 and 2026 |
| ^ $ \b | anchors and word boundary | \bcat\b not caterpillar |
| ( ) (?<name> ) | capturing and named groups | (\d{4})-(\d{2}) |
| | | alternation | cat|dog |
| *? +? ?? | lazy: match as little as possible | <.+?> stops at the first > |
Groups are results, not just syntax
Every parenthesis pair that captures can be read back after a match: group(0) is the whole match, group(n) is the nth pair, and named groups give the same values readable names. This is how a pattern becomes a parser: one pass extracts year, month and day into typed fields.
Non-capturing groups (?...) group for the quantifier without adding a slot to the result, which keeps group numbering stable when the pattern grows.
Matcher dm = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})").matcher("2026-09-21"); if (dm.matches()) { System.out.println(dm.group(1)); // 2026 } m.group("user"); // (?<user>\\w+) names the slot
Greedy, lazy, possessive
Quantifiers are greedy by default: <.+> grabs the longest span that lets the rest of the pattern succeed, so it eats from the first < to the last >. Adding ? flips it to lazy, which stops at the first > it can. The table shows both against the same input.
A possessive quantifier (+ after the quantifier, like .*+) grabs and never gives back; it exists for performance, at the price of rejecting matches that require backtracking. Lazy is about the result, possessive is about the engine.
"<a><b>".replaceAll("<.+>", "X"); // X (one greedy match, first < to last >) "<a><b>".replaceAll("<.+?>", "X"); // XX (two lazy matches)
Regex workbench · where the pattern bites
pick a patterninput
find() walks two matches
The API surface you actually use
find walks matches; replaceAll and replaceFirst substitute with $1-style group references; split divides the string on every match. Together these four cover the overwhelming majority of real usage.
"2026-09-21".replaceAll("(\\d{4})-(\\d{2})-(\\d{2})", "$3.$2.$1"); // 21.09.2026 "go,java;;rust".split("[;,]"); // [go, java, , rust]
split takes a regex, not a literal: splitting on "." splits on any character. Escape what should be literal, or reach for Pattern.quote("...").
Flags change the whole pattern
Flags go in the compile call or inline after (? : CASE_INSENSITIVE for letters, MULTILINE so ^ and $ match per line, DOTALL so . includes newlines, COMMENTS to allow whitespace and # comments inside long patterns. A pattern with COMMENTS becomes readable enough to review, which matters once patterns grow past one line.
Pattern.compile("hello", Pattern.CASE_INSENSITIVE).matcher("HELLO").matches(); // true Pattern.compile("^item", Pattern.MULTILINE); // ^ applies per line, not per input
The traps that bite in production
Backtracking is the classic performance trap: a pattern like (a+)+b on a long run of a's explores an exponential number of ways to split them before failing. Prefer precise character classes and possessive quantifiers when the risk is real, and never run an unbounded user-supplied pattern over unbounded input.
The other traps are smaller and just as common: treating user input as a pattern where it should be literal (use Pattern.quote), forgetting that splitting is regex-based, and writing \\d in Java source when the regex needs \d.
- Literal text: Pattern.quote(input) wraps it into \\Q...\\E so no character is special.
- Catastrophic backtracking: nested quantifiers like (a+)+; keep classes tight and anchors explicit.
- Double escaping: the Java string needs \\d, the regex engine sees \d.
- matches vs find: whole-string versus search; the number one silent mismatch.
- Compile in a loop: hoist Pattern.compile out of the hot path.
A regex is a program
Small ones are perfect for validation and extraction; large ones are unreadable, untestable and slow in ways that surface only under load. When a pattern stops fitting in one glance, it is time for code that parses instead.
Interview angles
matches versus find?+
matches requires the entire input to match the pattern; find searches for the next occurrence anywhere and is used in a loop with group() access. Regex tools and languages often default to search, so porting a pattern that 'worked' often needs find or explicit anchors.
What is the difference between greedy, lazy and possessive quantifiers?+
Greedy takes as much as possible then backtracks to let the rest match; lazy takes as little as possible then expands; possessive takes as much as possible and never backtracks, trading matches for speed and predictability.
Why is String.split(".") wrong?+
split takes a regex and . means 'any character', so the string is split at every position. Escape it: split("\\."), or use Pattern.quote for text that may contain any special characters.
What is catastrophic backtracking?+
Patterns with nested quantifiers ((a+)+, (a|aa)+) can explore exponentially many backtracks on inputs that almost match, hanging the thread. Fix with precise classes, possessive quantifiers, or by not running untrusted patterns.
When should a regex not be used?+
For structured formats with nesting (JSON, HTML, code) and for anything where partial understanding is dangerous. Regex shines on flat, regular tokens: validation, extraction, splitting, simple rewriting.