Learn regular expressions · Lesson 11
Backtracking
Most regex engines work by backtracking. They read the pattern left to right, and at every choice (an alternative, one more repetition or one fewer) take the first option and remember the others. When the rest fails, they go back to the last choice and try the next. That’s how ".*" in the last lesson found its closing quote: .* took the whole line, and gave it back a character at a time.
Most of the time this is fast. But the number of ways to try can grow very quickly with the text, and a pattern that fails after trying them all can take seconds, minutes or years.
Catastrophic backtracking
(\w+\s?)+$ is meant as “words, each perhaps followed by a space”. On text that matches, it’s quick. On a line of 30 letters followed by something that can’t match, say a !, every way of splitting the letters among the repetitions gets tried before the engine gives up:
(\w+\s?)+$ on aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!
\w+ can take 30 letters, or 29 and leave one to the next round, or 28 and two rounds of one, and so on: over half a billion ways to cut 30 letters into rounds, each tried and failed. Every letter more doubles it. This is catastrophic backtracking. If an attacker can supply such input, the result can be a regular-expression denial-of-service attack, or ReDoS: one request that keeps a server busy. It has taken real sites down: Stack Overflow in 2016, on a line of 20,000 spaces; Cloudflare in 2019, on a pattern in its firewall rules.
The cause is always the same: the pattern can match the same text in more than one way, inside a repetition. Here, \w+ repeated by +, with \s? allowed to match nothing, so nothing separates one round from the next.
Writing it so it can’t
Make every way through the pattern different, so there’s only one way to match any text. The words-and-spaces pattern, written so a space has to separate the rounds:
/^\w+(?:\s\w+)*$/1 matchone two threeTry it in Dotstar →
Now \w+ can’t split a word between rounds, because each round after the first starts with a space. Other remedies:
- A negated class instead of
.*, as in the last lesson:"[^"]*"can’t backtrack into the quotes. - An atomic group,
(?>…), or a possessive quantifier,++: once it has matched, the engine doesn’t go back into it.(?>\w+\s?)+fails at once. - A time limit on matching, where the language has one.
Dotstar underlines a pattern that can backtrack catastrophically as you write it, with why, and offers a safer form where it can; the debugger shows each step the engine takes. Dotstar also stops a match that runs too long, so the app carries on.