Regular languages and linear-time engines

Advanced · 25 min

Why some engines cannot blow up. Simulate every possible match at once, what you give up (backreferences, lookaround), and what no regex can match.

Before thisCatastrophic backtracking and ReDoSAtomic groups and possessive quantifiersBackreferencesLookahead

Kay Lack · 32 min · from 3:32

Regular languages and linear-time engines

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Kay LackReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A backtracking engine follows one path and undoes it. A linear-time engine follows all paths in lockstep, keeping the set of states it could be in. Time is proportional to input length times pattern size.
  • My 40-line simulation matched (a+)+ against 300,000 a's and a ! in 71 ms, with at most 4 active states, on the input that takes a backtracking engine years.
  • The guarantee has a price. Go's regexp, Rust's regex (via rg) and RE2 reject backreferences and lookaround, because they need memory of earlier text that a finite set of states cannot hold.
  • A pure regex has finite memory, so it cannot match balanced parentheses to any depth. A pattern limited to depth d grows with d and fails at d+1. PCRE and Perl add recursion, which is no longer regular.
  • Linear time is about growth, not speed. Pick a linear engine for untrusted input, a backtracking one when you need backreferences or lookaround.

Following every path at once

The last two lessons dealt with a bad failure mode: the engine follows one path, discovers a dead end, and returns to try another, over and over. There is a different way to build the machine, and it removes that mode entirely.

Instead of choosing a path and undoing it, follow all of them at once. After reading each input character, keep the set of every position in the pattern you could now be at. Read the next character, and compute the next set from the current one. Nothing is ever undone, because nothing was committed. Think of a crowd of people each tracing a different route through a transit map while a single clock ticks. At each tick, you only ask who is still on the map and where.

Russ Cox’s 2007 article “Regular Expression Matching Can Be Simple And Fast” credits Ken Thompson’s 1968 paper with introducing this multiple-state simulation. It reports that Perl, PCRE, Python and Ruby were at that time all using recursive backtracking, and that Perl needed over sixty seconds on a 29-character case where the Thompson simulation took twenty microseconds. That article is from 2007. Today’s Perl behaved differently when I tested it, as the previous lesson showed.

Watch it run

I wrote a small matcher in JavaScript (about 40 lines): it compiles literals, ., |, *, +, ? and groups into a state graph, then simulates it with a set of active states. It counts every time a state is added. Here it is on the pattern that took a backtracking engine seconds:

(a+)+  on n a's then !    n=30      steps=121       max-active=4   0.0 ms   match=false
                          n=3000    steps=12001     max-active=4   1.5 ms
                          n=300000  steps=1200001   max-active=4   70.6 ms
(a|a)+ on n a's then !    n=300000  steps=1500003   max-active=5   87.2 ms

The pattern compiles to 4 states, and the number of states active at once never exceeded 4. Steps grew as about 4n. Ten times more input meant ten times more steps, which is linear. The same pattern on a matching string ran in the same time, since there was no early exit to benefit from. The simulation also visited only two distinct state sets in total, and a real engine caches those: each distinct set becomes one state of a deterministic automaton, so after warm-up the matching loop does one table lookup per character.

This is a toy: no capture groups, no anchors beyond a full-string match, no leftmost rules. It shows the idea, not a production engine.

The real ones, and what they refuse

Go regexp   ^(a+)+$ on 1,000,000 a's then !     40 ms
rg (Rust)   ^(a+)+$ on 100,000 a's then !       about 20 ms for the whole process
V8 /l flag  /^(a+)+$/l on 100,000 a's then !    3 ms

Go’s regexp package follows the RE2 syntax. The Rust regex crate sits inside rg, which I ran from this machine’s bundled ripgrep 14.1.1. V8’s l flag is behind --enable-experimental-regexp-engine on Node 26 and is experimental. I did not run RE2 itself.

All three refuse the same features:

go     (a)\1       invalid escape sequence: `\1`
go     a(?=b)      invalid or unsupported Perl syntax: `(?=`
rg     (a)\1       error: backreferences are not supported
V8 /l  (a)\1       Cannot be executed in linear time
V8 /l  a(?=b)      Cannot be executed in linear time

Both are things the lockstep method cannot do. A backreference needs the engine to remember an arbitrary stretch of earlier text and compare against it. A set of pattern states is finite, so it cannot hold a string of any length. Lookaround would need an extra independent scan from every position. Go also rejects a{1001}, a repeat count above its limit, and atomic groups and possessive quantifiers ((?>, ++): they are unneeded where nothing backtracks.

Semantics also differ in a smaller way. Go’s default matching is leftmost-first like Perl: cat|category on category returned cat. Go’s MustCompilePOSIX returned category, the leftmost-longest rule. That is the same split as the BSD grep -E result in lesson 36.

What no regex can match

A pure regular expression has a fixed amount of memory: its state set. That is why it can match a+ and cannot count. Try balanced parentheses. You can write a pattern for depth up to d by nesting, and I generated it for several d:

depth limit   pattern length   handles depth d   handles depth d+1
1             11               true              false
2             20               true              false
3             29               true              false
5             47               true              false
10            92               true              false

Each extra level costs 9 more characters and the pattern still fails one level deeper. There is no finite pattern for all depths. This is the reason a regex is the wrong tool for HTML or JSON, covered in when not to use a regex.

Backreferences let a regex in a backtracking engine step past the limit in a limited way: ^(a+)b\1$ matched aabaa and aaabaaa and rejected aaba in JavaScript, and it is not a regular language. PCRE and Perl also have recursion: ^(\((?1)*\))*$ accepted (()), ()() and a nine-deep nest and rejected (() and ((()))(( in both pcre2grep and Perl. Those features are why they are not linear.

For the formal background, including what makes a language regular, see finite automata and regular languages and lexing and parsing.

Speed is a separate question

A linear guarantee is about how time grows. It does not mean fast. Go matched ^a+$ against a million as in 15 ms in my run; V8 ran ^a+$ on a million as plus a ! in 0.7 ms. Backtracking engines are often quicker on ordinary input and then hit the wall on a bad one. If the pattern is a fixed internal constant and the input is yours, use whatever is convenient. If the input is an attacker’s, prefer a linear engine or cap the input length.

About the video

“How regexes got catastrophic” by Kay Lack was published 23 November 2024 and runs 32 minutes 29 seconds. The description gives chapters for “Backtracking and lockstep”, “ReDoS”, “Backreferences” and “Exercises”, and I clipped from the start of the lockstep chapter to the end of the backreferences chapter. The chapters suggest it contrasts one-path backtracking with lockstep simulation, which is this lesson’s core, and also reaches backreferences. I couldn’t read a transcript, so I can’t confirm it names RE2 or Rust’s regex, or that it says what a regular language is. The description also lists a prime-number regex at a timestamp (50:00) that is past the video’s length, so I ignored that line. English per its title and description.

What I did not run

RE2 directly, Rust’s regex crate outside of rg, .NET’s balancing groups, and the NFA-to-DFA conversion beyond counting distinct state sets in my toy. The result that regexes without backreferences describe exactly the regular languages (Kleene) is from memory, not checked here.

Next

Knowing the engine tells you what makes a pattern slow. Writing patterns that run fast turns that into habits.

Check yourself

  1. 01How does a linear-time engine avoid backtracking?

    It reads the input once, left to right, and keeps the set of every state the pattern could be in after each character. Nothing is undone, so each character costs at most the number of states in the pattern.

  2. 02Why can't RE2 or Go's regexp support \1?

    A backreference needs to remember an arbitrary piece of earlier text. A finite set of states cannot store a string of unbounded length, so the lockstep method has nowhere to keep it. Go's regexp rejects \1 at compile time.

  3. 03Can a pure regular expression check that parentheses are balanced?

    Not to any depth. It would have to count open parentheses without limit, and a finite automaton has a fixed number of states. You can write a pattern for a fixed maximum depth, but it gets longer with each level and fails one level deeper. Use a parser or a recursion-capable flavour.

  4. 04What does a linear-time guarantee not promise?

    It does not promise speed. It promises that doubling the input at most doubles the time. In my test Go matched a million a's against ^a+$ in about 15 ms, slower than V8 on a similar pattern.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark