Regular expressions that do not hang: understanding catastrophic backtracking
A regular expression can pass every test, run for years, and then freeze a server on one unusual input of forty characters. The cause is almost always the same, it is easy to spot once you know the shape, and it has a name: catastrophic backtracking.
How a backtracking engine works
The regex engines built into JavaScript, Python, Java, PHP, Ruby and .NET work by trial and error. They try to match the pattern from left to right, and whenever there is a choice (how many characters a + should take, which side of a | to use) they pick one option and remember the others. If the match later fails, they go back to the most recent choice and try the next option. That is backtracking.
Usually this is fast because there are few choices. The trouble comes when a pattern lets the same piece of text be divided up in many different ways, and the overall match fails. The engine must then try every division before it can report "no match".
The classic example
^(a+)+$
This looks harmless: one or more groups of one or more a. On aaaa it matches at once. Now try a string of as followed by one character that cannot match:
aaaaaaaaaaaaaaaaaaaaaaaa!
The ! guarantees failure, but the engine does not know that until it has tried every way of splitting the as between the inner and the outer +: one group of 24, a group of 23 and a group of 1, and so on. For n letters there are 2n−1 ways. Each extra character doubles the time. Around 25 characters takes a noticeable pause; 35 can take minutes.
When untrusted users can supply the input, this is a denial-of-service weakness, usually called ReDoS. Real outages have been caused by a single such pattern in a validation rule.
How to recognise a dangerous pattern
Three shapes account for nearly every case. In each, look for a repeated part whose text could be matched in more than one way.
1. A quantifier inside a quantifier
(a+)+ (\w*)* (\d+)* (.*,)*
If the inner part can match the same characters with different numbers of repetitions, the outer repetition multiplies the possibilities.
2. Alternatives that overlap, repeated
(a|aa)+ (\w|\d)+ (.|\s)*
A digit matches both \w and \d, so every digit doubles the number of paths.
3. Adjacent repeats that can match the same characters
\s*\s*$ .*.*=.* \w+\s*\w+
These grow more slowly (the time is a power of the input length rather than exponential), but on inputs of a few thousand characters they still take seconds. A pattern such as ^\s+|\s+$ used to trim a very long line of spaces is a well-known example.
The trigger is always the same kind of input: a long run that fits the repeated part, followed by something that makes the whole match fail.
Fixes, from simplest to strongest
Remove the redundant quantifier
Nested quantifiers are often an accident. (a+)+ matches exactly the same strings as a+. (\w+\s?)* can usually be written as [\w\s]*.
Make each character matchable in only one way
Replace a vague .* with a class that says what you really want to skip over. To match a quoted string:
".*" ← greedy, runs past the closing quote
".*?" ← works, but backtracks one step per character
"[^"]*" ← each character has exactly one role
The third form cannot backtrack inside the quotes, because a quote character can never be part of [^"]*. The same idea fixes separated lists. Instead of (\w+,?)+, write the structure out:
^\w+(,\w+)*$
Here a comma must come between words, so there is only one way to divide the input.
Make alternatives mutually exclusive
Rewrite (\w|\d)+ as \w+. If the branches of an alternation can start with the same character, reorder or merge them until they cannot.
Stop the engine from reconsidering
Some engines offer atomic groups (?>...) and possessive quantifiers a++, which tell the engine not to backtrack into what it has matched. Java, PCRE (PHP), Ruby and .NET support them, and Python added both in version 3.11. JavaScript has neither, but a lookahead followed by a backreference gives the same effect, because a lookahead is never re-entered:
(?=(\w+))\1
Limit the input and the time
Check the length before applying a regex. An email field has no reason to accept 50,000 characters. Where the platform supports it, set a timeout: .NET accepts one per regex, and other platforms can run the match in a worker that is terminated if it takes too long.
Use an engine that cannot backtrack
RE2 (and the engines in Go and Rust that follow the same design) guarantee time proportional to the length of the input, by giving up features that require backtracking: backreferences and lookaround. For patterns applied to input you do not control, this is the strongest protection there is.
How to test a pattern
Ordinary tests use short, valid inputs, which is exactly the case that never backtracks. Add one more kind of test for any regex that touches user input:
- Find the repeated part of the pattern.
- Build an input that repeats text matching that part 30 times, then 60 times.
- Append a character that makes the whole match fail.
- Time both. If doubling the length roughly doubles the time, the pattern is safe. If the time multiplies by four or more, or the 60-character version never returns, you have found a problem.
You can try this in the Regex Tester: paste ^(a+)+$, type a run of the letter a, add an exclamation mark, and extend the run a few characters at a time. Stop when you feel the delay; it grows quickly.
A note on validation
The patterns most often involved in these incidents are attempts to validate something fully with one regex: email addresses, URLs, HTML. Those grammars are complicated, and patterns that try to cover them completely are long, hard to review and full of nested repetition. A simple check (for an email: some text, an at sign, some text, a dot, some text) followed by a real test, such as sending a confirmation message, is both safer and more accurate.