Section 12.44

Regular expression

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:

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.

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 nn 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 n=3n = 3, 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 n−1n - 1 gaps between neighboring letters, and at each gap a new repetition either starts or does not, independently, so there are 2n−12^{n-1} ways. For n=3n = 3 that is 22=42^2 = 4, as listed; for n=4n = 4 it is 23=82^3 = 8; for n=30n = 30 it is 229=536,870,9122^{29} = 536{,}870{,}912.

Python’s re tries them all. On one desktop computer with Python 3.12, the rejection took about 0.022 s for n=20n = 20 and 0.088 s for n=22n = 22: two more letters, 0.088/0.022=4=220.088 / 0.022 = 4 = 2^2 times the time. Continuing the doubling, n=30n = 30 needs about 0.088×28≈230.088 \times 2^{8} \approx 23 s, and n=40n = 40 about 0.088×218≈23,0000.088 \times 2^{18} \approx 23{,}000 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 nn 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 n2n^2. In the same measurement, doubling nn from 10,000 to 20,000 multiplied the time by about 4, from 0.028 s to 0.11 s.

Stated precisely

Let Σ\Sigma be a finite alphabet. The regular expressions over Σ\Sigma, and the set of strings, called the language, that each one denotes, are defined as follows. ∅\emptyset denotes the empty set; ε\varepsilon denotes the set holding only the empty string; each character c∈Σc \in \Sigma denotes {c}\{c\}. If rr denotes RR and ss denotes SS, then rsrs denotes {xy:x∈R,y∈S}\{xy : x \in R,\ y \in S\}, where xyxy is xx followed by yy; r∣sr \mid s denotes R∪SR \cup S; and r*r^{*} denotes every concatenation of zero or more strings from RR. Kleene’s theorem states that these languages are exactly the languages that finite-state automata accept [510].

Let mm be the length of the pattern and nn the length of the text. Thompson’s simulation takes time in O(mn)O(mn), in Big-O notation §14.2: at most a constant times m×nm \times n. A backtracking engine that does not remember which pairs of text position and pattern position have already failed can take time exponential in nn; for (a+)+ against nn letters a followed by !, it reaches at least 2n−12^{n-1} 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 nn letters a into repetitions in 2n−12^{n-1} 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].