Lesson 1 of 13 · 22m
How Regex Engines Actually Match
Backtracking versus automata engines, what a choice point costs, and the mental model that lets you predict a pattern's behavior before you run it.
A regex is not a description of a string. It is a program, and the engine interpreting it decides whether that program runs in microseconds or until your health check times out. Every validator, every WAF rule, every grep one-liner executes one of two ways, and the two ways have opposite failure modes.
Two families of engines
| Family | Who uses it | Guarantee | What it gives up |
|---|---|---|---|
| Backtracking | Perl, PCRE2, Python re, Java java.util.regex, JavaScript (V8's Irregexp), .NET, Ruby, PHP | Rich features: backreferences, lookarounds, lazy and possessive quantifiers, conditionals | Worst case is exponential in input length |
| Automata (Thompson NFA / DFA) | RE2, Go regexp, Rust regex, GNU grep, mawk | Linear time in input length, always | Backreferences and lookarounds |
A backtracking engine is depth-first search over your pattern. At every choice point — a * that could take one more character, an alternation with an untried branch — it pushes a bookmark and commits to the first option. When the path fails, it pops the most recent bookmark and tries the next one. Failure is proven only when the bookmark stack is empty. An automata engine keeps every viable state alive at once and advances all of them per input character, so there is nothing to pop and nothing to retry.
Watch a backtracker think
pattern: ".*"
input: say "hi" and "bye"
1. scan forward to the first " -> index 4
2. .* is greedy: it eats to end of input -> hi" and "bye"
3. need a closing " but input is exhausted -> FAIL, backtrack one char
4. give back e, y, b ... none is a " -> keep backing off
5. give back the final " -> closing " matches
result: "hi" and "bye" (not "hi")Three ways to write "a quoted string," three different costs:
const line = 'say "hi" and "bye"';
console.log(line.match(/".*"/)[0]); // "hi" and "bye" greedy: overshoot, then give back
console.log(line.match(/".*?"/)[0]); // "hi" lazy: creep one char at a time
console.log(line.match(/"[^"]*"/)[0]); // "hi" one way to match, zero retriesThe third is the professional answer. It does not lean on the engine's search strategy at all: [^"]* can never consume a quote, so exactly one match is possible and the engine either finds it or fails in a single pass. Greedy and lazy are not correctness tools — they pick which of several possible matches you get first. The negated class removes the ambiguity entirely.
Leftmost is the only guarantee
Both families return the leftmost match — the one starting at the earliest input position. They disagree about which match when several start there. Backtracking engines commit to the first alternative that succeeds: /ab|abcd/ on abcd gives ab. POSIX automata return the longest: grep -oE 'ab|abcd' prints abcd. Neither is "right"; they are different specs. When you need a specific result, write the pattern so only one is possible instead of hoping the engine's policy agrees with you.
Why automata engines refuse features
A backreference like (\w+) \1 requires remembering what matched, which makes the language non-regular — matching with backreferences is NP-hard in general. RE2-family engines drop the feature rather than the guarantee. In Go, regexp.Compile("(a)\\1") returns error parsing regexp: invalid escape sequence (and regexp.MustCompile panics on it). That is not a bug; it is the bill for never hanging.
Field notes
- Know which engine your tool uses before a pattern sees untrusted input. "It's just a regex" is how ReDoS tickets start — the catastrophic-backtracking lesson covers the outage receipts.
- Cost scales with ambiguity: the more ways a pattern can match the same run of characters, the more paths the engine explores.
- The expensive case is the failed match. A benchmark over inputs that match tells you nothing — test near-misses.
- Compile once.
String.matches()in Java compiles on every call, andPattern.compileinside a loop is a classic hot spot. Python caches the 512 most recent patterns, but hoisting is still free.
Keep reading
Related articles from the SudoSecurity blog.
Java Pulled Primitive Patterns After Five Previews. JDK 28 Won't Compile Them.
Primitive types in patterns, instanceof, and switch previewed in every JDK from 23 to 27. On November 9 the Amber team withdrew the feature, and it won't be in JDK 28 even with --enable-preview. Here's why Valhalla changed the plan, what replaces it, and how to rewrite code that used it.
.NET 11 Is Out. Union Types Got the Applause, but unsafe Is What Changed.
.NET 11 shipped on November 10, 2026, and C# 15 finally has union types, the feature people have asked for since pattern matching arrived.
PHP 8.6 Finally Turns On the Session Settings You Were Told to Set in 2006
Every PHP hardening guide for two decades has told you to flip the same three session settings. PHP 8.6, due November 19, 2026, flips them for you: strict mode on, HttpOnly on, SameSite set to Lax.
Rust 1.100: The Never Type Is Finally Stable, and Cargo Learned to Wait
Rust 1.100 stabilizes the never type after ten years and five failed attempts, along with the core Allocator API and a DropGuard helper. The change most teams will notice is in Cargo: a one-line config that makes it skip any crate version published in the last few days.