Definition
A regular expression is a pattern, written in a small language, that describes a set of strings. A matcher, called a regular-expression engine, decides whether a given text, or a part of it, belongs to that set. In the formal sense of computer science, a regular expression is built from single characters with three operations: concatenation (one part followed by another), alternation (either part, written |) and repetition (zero or more times, written *). Programming languages add character classes, counted repetition, anchors and backreferences; Python’s §12.23 re module provides them.
The idea
A program must accept a version field such as 1.12.3 and reject everything else. Checking it by hand takes a loop with counters and several branches. The pattern [0-9]+\.[0-9]+\.[0-9]+ says the same in one line: digits, a dot, digits, a dot, digits. Regular expressions exist because many input checks and text searches have this form: a shape that can be described without counting nested brackets.
The pattern says what to match, not how. An engine can match it in two very different ways. A backtracking engine follows one guess at a time and, when a guess fails, goes back to the most recent choice and tries the next option, like a person in a maze who always returns to the last fork. An automaton-based engine follows every possible guess at once, like a group that splits up at every fork, walks all corridors in step, and merges whenever two members reach the same spot. The group finishes in one pass. The lone walker, in a maze with many forks that all end in dead ends, may walk the same corridors an enormous number of times. The picture stops at one point: a maze has a fixed number of spots, and the group stays small only because of that; in the engine, the spots are the positions in the pattern, so the group never outgrows the pattern.
How it works
Pattern pieces in Python’s syntax:
A literal character matches itself.
.matches any character except a newline. A backslash removes a special meaning, so\.matches a dot.A class
[a-z0-9]matches one character from the set, and[^"]one character not in it.\dmatches a digit.Repetition:
*(0 or more times),+(1 or more),?(0 or 1),{m,n}(from to times). Repetition is greedy: it first takes as much as possible.Alternation
|, and grouping with parentheses.Anchors:
^matches at the start,\Zonly at the very end, and$at the end or just before a newline at the end.A backreference
\1matches the same text that group 1 matched. Backreferences describe sets of strings that no formal regular expression describes.
Search operations. re.fullmatch(p, s) succeeds only if the pattern p matches all of s. re.match requires only a match that starts at the beginning of s, and re.search accepts a match anywhere. For validation, fullmatch is the right call: re.search(r"[0-9]+", "12; rm") succeeds, because the text contains digits somewhere.
Two engine families.
Automaton-based engines translate the pattern into a finite-state automaton §8.33, a machine with a fixed set of states that reads the text one character at a time, and run it over the text. The method that Ken Thompson published in 1968 [509] tracks the set of states the automaton could be in; that set never holds more states than a fixed multiple of the pattern’s length. RE2, a library from Google, the
regexppackage of the Go language and theregexlibrary of the Rust language work this way. Their time grows in proportion to the length of the text times the size of the pattern, and they do not support backreferences.Backtracking engines try one way of matching at a time and, on failure, return to the most recent choice (which alternative, how many repetitions) and try the next one. Perl, PCRE (Perl Compatible Regular Expressions), Java, JavaScript and Python’s
rework this way. They support backreferences and other extensions, but in the worst case they try every way of matching before they can report failure.
Ambiguity and its cost. A pattern is ambiguous on a text when it can match that text in more than one way. Typical shapes are a repetition inside a repetition, as in (a+)+; a repetition of alternatives that overlap, as in (a|aa)*; and two neighboring repetitions that can take the same characters, as in \d+\d+. When the text then fails to match at its end, a backtracking engine must reject every way before it can answer no, and the number of ways can grow exponentially with the length of the text. An attacker who chooses the text, and knows or guesses the pattern, can make one match run for minutes or hours: a regular-expression denial of service §1.28 (ReDoS), a form of algorithmic complexity attack §15.35. In July 2019 a single regular expression in a web firewall rule caused a worldwide outage of Cloudflare’s network in this way.
Worked example
Take re.fullmatch(r"(a+)+", s), where s is letters a followed by !. The ! can never match, so the answer is no. Count the ways in which the pattern can cover the letters. For , writing each repetition of the outer group in brackets, the ways are [aaa], [a][aa], [aa][a] and [a][a][a]: 4 ways. In general there are gaps between neighboring letters, and at each gap a new repetition either starts or does not, independently, so there are ways. For that is , as listed; for it is ; for it is .
Python’s re tries them all. On one desktop computer with Python 3.12, the rejection took about 0.022 s for and 0.088 s for : two more letters, times the time. Continuing the doubling, needs about s, and about s, more than 6 hours, for a text of 41 characters.
The repair is to remove the ambiguity. a+ accepts exactly the same strings as (a+)+, a run of one or more letters a, but matches each text in only one way, and re.fullmatch(r"a+", "a" * 40 + "!") answers no in microseconds. Since Python 3.11, re also offers possessive repetition, (a++)+, and atomic groups, (?>a+)+; both forbid the engine to go back into the group, and both also answer no at once here.
Ambiguity need not be nested to hurt. re.search(r"a*b", s) on a text of letters a and no b tries every start position, and from each one it extends a* to the end of the text and steps back over every letter before failing, so the work grows with . In the same measurement, doubling from 10,000 to 20,000 multiplied the time by about 4, from 0.028 s to 0.11 s.
Stated precisely
Let be a finite alphabet. The regular expressions over , and the set of strings, called the language, that each one denotes, are defined as follows. denotes the empty set; denotes the set holding only the empty string; each character denotes . If denotes and denotes , then denotes , where is followed by ; denotes ; and denotes every concatenation of zero or more strings from . Kleene’s theorem states that these languages are exactly the languages that finite-state automata accept [510].
Let be the length of the pattern and the length of the text. Thompson’s simulation takes time in , in Big-O notation §14.2: at most a constant times . A backtracking engine that does not remember which pairs of text position and pattern position have already failed can take time exponential in ; for (a+)+ against letters a followed by !, it reaches at least dead ends, one for each way of dividing the letters. The bound belongs to the engine, not to the pattern: the same pattern takes linear time in RE2 and exponential time in Python’s re.
Limits and common mistakes
A regular expression in the formal sense cannot describe nesting to any depth, such as balanced parentheses, because a finite-state automaton cannot count without limit. Some engines, such as PCRE, add recursion, but a parser states such a format more clearly.
$ also matches before a final newline: re.match(r"^[a-z]+$", "abc\n") succeeds. Validate with fullmatch, or end the pattern with \Z.
In a pattern for Python text strings, \d matches every Unicode §12.48 decimal digit, such as the Arabic-Indic digit three (code point U+0663), not only 0 to 9. Write [0-9], or pass the flag re.ASCII, when only the ten digits 0 to 9 are allowed.
Python’s re has no time limit of its own. Running the match in a separate process that is killed after a limit bounds the damage, but it does not make the matcher faster, and the attacker still costs one full time limit per request. Limiting the length of the input before matching also bounds the damage.
Never build a pattern from untrusted text without re.escape: whoever chooses the pattern can choose an ambiguous one.
Automaton-based engines such as RE2 guarantee linear time but reject backreferences and lookaround, the constructs that test what precedes or follows a position without consuming it.
Tests with ordinary inputs show neither the worst case nor every difference in the accepted strings. Rewriting a pattern for speed can change which strings it accepts; check both, for example with property-based testing §10.7 or fuzzing §10.9.
Questions answered
Can ambiguous patterns cause excessive backtracking on adversarial input?
Yes. When a pattern can match the same text in many ways and the match finally fails, a backtracking engine, such as Python’s re, Perl, PCRE (Perl Compatible Regular Expressions), Java or JavaScript, tries the ways one after another before it can answer no, and the number of ways can grow exponentially with the length of the text. The pattern (a+)+ can divide letters a into repetitions in ways, so re.fullmatch(r"(a+)+", "a" * 40 + "!") runs for hours on a desktop computer, although the text has only 41 characters. An attacker who controls the text can use this as a denial of service, called ReDoS (regular-expression denial of service).
The defenses are: remove the ambiguity, so that each text can be matched in only one way (a+ instead of (a+)+); use possessive repetition or atomic groups where the engine has them; limit the input length before matching; never build a pattern from untrusted text without re.escape; or use an automaton-based engine such as RE2, whose time grows only linearly with the length of the text but which does not support backreferences. Tests on ordinary inputs say nothing about this worst case.
Related entries: Algorithmic complexity attack (§15.35), argparse (§12.37), Boundary-value testing (§10.31), Asymptotic complexity (§14.2), Denial of service (DoS) (§1.28), Finite-state machine (§8.33), Worst-case versus average-case complexity (§14.3), Property-based testing (§10.7), Fuzzing (§10.9). Further reading: [130, 509, 510].