Finite automata and regular languages
Finite automata model computation with bounded memory. This lesson develops DFAs, NFAs and the subset construction, regular expressions and Kleene's theorem, the pumping lemma and Myhill-Nerode, minimization and the Chomsky hierarchy, then builds a regular-expression engine without backtracking.
After this lesson you can
- Design DFAs and NFAs for given languages and prove correctness by induction over the input.
- Convert among regular expressions, NFAs and DFAs using Thompson's and subset constructions.
- Prove that a language is not regular using the pumping lemma and Myhill-Nerode.
- Minimize DFAs and reason about their minimum number of states.
- Explain catastrophic backtracking and build an engine that avoids it.
Before you start
Motivation: computation with bounded memory
A program that reads a stream of symbols once, from left to right, and stores only a fixed amount of information regardless of the stream’s length is a finite automaton. It is deliberately a limited model. It is the smallest model of computation that still does useful work, and its small size lets us analyze it completely. Almost every question about finite automata, such as whether two are equivalent, whether one accepts any string, or which equivalent automaton is smallest, has an exact algorithm. For more powerful machines, as you will see in the next lesson, those questions become undecidable.
Finite automata also appear throughout computing.
- Tokenizers and lexical analyzers. A compiler splits source code into identifiers, numbers, and operators with an automaton generated from regular expressions. Language models do something similar before BPE: a regular expression splits text into words, numbers, and punctuation. This is pretokenization.
- Input validation. Dates, addresses, identifiers, and web application firewall filters are commonly described using regular expressions.
- Constrained decoding. To make an LLM output only strings in a format such as a JSON schema, a date, or a function call, compile the format to an automaton and rule out tokens that cannot extend a valid prefix at every step. This is the idea of Willard and Louf (2023), which you will study as constrained decoding.
- Sequence models. An -gram model is a probabilistic finite automaton whose state is the last tokens, as in the n-gram Markov assumption.
There is also a security reason to understand this model. On July 2, 2019, a new Cloudflare firewall rule contained a regular expression whose critical part was .*(?:.*=.*). The backtracking engine executing it took superlinear time in the input length, exhausting the CPU of HTTP servers worldwide for 27 minutes, according to its public report. Three years earlier, in 2016, Stack Overflow was unavailable for 34 minutes because an expression removing trailing spaces encountered a post containing around 20,000 consecutive spaces. Neither expression required backtracking: both describe regular languages, which a finite automaton decides in linear time. This failure is called ReDoS, regular-expression denial of service. It is a common risk for systems accepting external text, including the attack surface of ML systems.
This lesson builds the theory: deterministic and nondeterministic automata and their equivalence, regular expressions and Kleene’s theorem, the limits of regular languages through the pumping lemma and Myhill-Nerode, minimization, and the Chomsky hierarchy. At the end, you will build a regular-expression engine from scratch that never backtracks and compare it with Python’s re module.
Strings and languages
An alphabet is a nonempty finite set of symbols. We will usually use or . A string over is a finite sequence of symbols, and is the set of all such strings. With the notation of inductive definitions, is the smallest set containing the empty string and, whenever it contains , also containing for every . This definition underlies every induction on input length in the lesson.
We write for length, for concatenation, with , for repeated times, and for the number of occurrences of symbol . A language is any subset . Besides the usual set operations, union, intersection, and complement , languages have two further operations:
where . The operation is the Kleene star, concatenation of any number of pieces of , including zero pieces.
One size distinction is worth keeping in mind. is countable, but the set of languages is not, by Cantor’s diagonal argument. Every computational model we study, including automata, grammars, and Turing machines, has a finite textual description, so there are only countably many of them. Almost all languages therefore cannot be recognized by any machine. We are interested in those that can.
Deterministic finite automata
Draw the automaton as a directed graph with a vertex for each state, an edge for each , an incoming arrow marking , and a double circle for accepting states. Reading follows the unique walk from labeled , and acceptance means ending in . It matters that is a total function: exactly one edge leaves each state for each symbol. A missing edge in a diagram implicitly leads to a sink, a rejecting state that cannot be left.
Directly from the definition, follows by induction on : the state after reading summarizes everything the automaton will use from . A useful way to design a DFA is to ask of each state what must be remembered about the prefix read so far, and check that this information can be updated one symbol at a time.
A proved example: binary multiples of 3
Read a binary number from its most significant bit and decide whether it is divisible by 3. Let be the number represented by , with and leading zeroes allowed. There is no need to remember the unbounded integer, only its remainder modulo 3. If a prefix has value and bit arrives, the new value is and its remainder depends only on that of :
The DFA has , , and .
Proof
Use induction on . If , then . If and the assertion holds for , then
because reduction modulo 3 is compatible with sums and products. Finally, .
∎The statement that the state is is a loop invariant of the automaton simulator. To prove any DFA correct, write the prefix property represented by each state, check that satisfies it for , that every transition preserves it, and that are exactly the states whose property implies membership in the language.
The starting error is in . State means that the prefix ends in 1, but neither ends in 10 nor contains 101. If another 1 arrives, the prefix ends in 11, whose longest suffix that is also a prefix of 101 is still 1. The automaton should remain in . With the wrong transition it forgets that 1 and rejects 1101. The tool does not try random strings. It searches breadth-first through reachable pairs of states, one from your automaton and one from the correct automaton, and stops at the first pair with different acceptance. Since there are finitely many pairs, finding none proves equivalence.
Operations and decision problems
Proof
Let be DFAs with . For complement, exchange accepting and rejecting states, . Since is total, each string ends in exactly one state, which accepts in the new automaton if and only if it did not in . For the other operations, the product automaton runs both at once, with states , initial state and . Induction on gives . Choosing as the accepting set yields ; gives union, and difference.
∎Viewing a DFA as a graph gives immediate algorithms for questions that have no general solution for more powerful models.
- Emptiness. if and only if no state in is reachable from . This reachability problem is solved by breadth-first search in time, and the search also returns the shortest accepted string.
- Equivalence. if and only if the symmetric difference is empty, an emptiness check on the product. If there is a disagreement, breadth-first search finds the shortest string, whose length is less than . This is what the figure above does.
- Finiteness. is infinite if and only if a cycle is reachable from and can reach .
Nondeterminism
In a DFA each symbol leads to exactly one state. A nondeterministic finite automaton relaxes this rule: a state may have several outgoing edges with the same symbol, none, or edges labeled that can be followed without reading input. It accepts if any path through the string ends in an accepting state.
The set contains exactly the states reached by walks of whose labels, after removing , form . This parallel reading is shown by the designer’s “ends in 01” example. After reading 0101, is active for the loop and for the now-confirmed hypothesis that the last two symbols are 01. The NFA carries all hypotheses at once.
Nondeterminism is a design tool. “Ends in 01” takes three states: stay in and at some point guess that the 0 being read is the penultimate symbol. transitions also make union straightforward: add a new initial state with two edges to the initial states of the two automata, as in the designer’s final example. Surprisingly, this adds no computational power.
The key is that for every . The DFA’s state is the NFA’s active-state set. You will prove this by induction on in the exercises. The idea that nondeterminism can be eliminated by remembering sets is the subset construction, the result for which Rabin and Scott received the 1976 Turing Award. In practice, instead of all subsets, construct only those reachable from by breadth-first search. Sometimes there are few reachable subsets; sometimes there are many.
The explosion is inevitable.
Proof
The NFA is the one in the figure: has a loop for 0 and 1, and for , with . For the lower bound, let be a DFA with and suppose two distinct strings of length reach the same state . Choose a position where they differ, with and , swapping names if necessary, and let . String has length , so its -th symbol from the end is at position and is . Therefore . Likewise, . But , and the DFA would accept both or neither. Thus the strings of length reach pairwise distinct states.
∎This is a special case of an idea we will soon name: two prefixes separated by some suffix cannot share a state. In practice, an NFA with states can be simulated in two ways with opposite costs. Simulating its state set, as in the designer, costs per symbol, counting each edge as an operation and assuming a bounded number of edges per state, for a total of without preprocessing. Compiling the DFA in advance costs per symbol, but compilation can require states. Real engines such as RE2 and Rust’s engine take a middle path: they construct DFA states lazily, only when visited by the input, and retain them in a bounded cache.
Regular expressions and Kleene’s theorem
The usual abbreviations are syntactic sugar: , , a character class , the dot for any symbol, and . For example, describes , and describes strings ending in .
The proof has two halves, both constructive algorithms.
From expression to automaton: Thompson’s construction. By structural induction on , construct an NFA with transitions satisfying three invariants: it has a single initial state with no incoming arcs, a single accepting state with no outgoing arcs, and at most two arcs leave each state. The cases are:
- Symbol : two states, . For , ; for , two states with no arcs.
- Concatenation : an arc from the final state of to the initial state of . The initial state is that of and the final state is that of .
- Union : a new initial state with arcs to the initial states of and , and a new final state with incoming arcs from both previous final states.
- Star : a new initial state and final state , with arcs from to the initial state of and to (zero repetitions), and from the final state of back to the initial state of and to (another repetition or exit).
Each case preserves the invariants and adds at most two states, so the NFA for has at most states. Here counts the symbols and the operators and (Thompson, 1968). These invariants matter. A seemingly cheaper star construction uses no new states, with an arc from the initial state of to its final state (to skip ) and another from final to initial (to repeat). It seems correct but is not: if the initial state of has incoming arcs, the skip becomes available midway through a path. With that recipe, works, and so does , but accepts : it reads , the loop in returns to the initial state, and the skip goes from there to the end without reading . The new initial state has no incoming arcs, preventing the skip after any input has been read.
From automaton to expression. Number the states of a DFA and write for a regular expression describing strings that go from to with every intermediate state in . For there are only direct arcs (and if ), giving a finite union of symbols. A path allowed to use state either does not use it, or goes from to , loops from to , and exits from to :
The language is the union of the with . This is the same recurrence as Floyd–Warshall for transitive closure, over the semiring of languages. The resulting expression can be exponential in , and in general this cannot be avoided.
Combining the three conversions, regular expressions, NFAs and DFAs are three ways to describe the same class of languages. Each is suited to a purpose: expressions for writing, NFAs for construction (union, concatenation and star are straightforward), and DFAs for execution and decision questions (complement, equivalence and minimization). For example, closure under complement is immediate for DFAs and far from obvious for expressions: what expression describes strings that do not contain 101?
What a finite automaton cannot do
A DFA with states cannot count beyond . If it reads more than symbols, the pigeonhole principle forces it to revisit a state. The input read between those two visits forms a loop that can be repeated any number of times without the automaton noticing.
This is the pumping lemma.
Proof
Let be a DFA for , and let . Take with and let and be the states it visits. Among there are states and only distinct ones, so for some . Take , and . Then and . Since , induction on gives , and hence .
∎The lemma is applied by contraposition, as a game against an adversary: the adversary picks , you pick with , the adversary picks a partition satisfying 1 and 2, and you pick with . If you win for every and every partition, is not regular.
The pumping lemma concerns one string at a time. The definitive result compares strings and gives an exact characterization.
Proof
(1 ⇒ 2) Let be a DFA for . If , then for every we have , so and . Thus strings in different classes reach different states: the index of is at most .
(2 ⇒ 1) Construct with one state per class: , , and . The transition is well defined: if , then for every , the suffix gives , that is, . is well defined too: with , implies . Induction on gives , and hence accepts if and only if .
(Minimal and unique) By the first part, every DFA for has at least as many states as there are classes, and attains that bound. If has exactly that many states, all are reachable (otherwise removing unreachable states would give a smaller DFA), and the map is well defined by the first part. It is surjective because each class is the image of . It maps finite sets of equal size, hence it is bijective. It also preserves the initial state, transitions and acceptance: is with renamed states.
∎This is the Myhill–Nerode theorem. To prove a language nonregular, exhibit infinitely many pairwise distinguishable strings. To prove a DFA minimal, exhibit as many pairwise distinguishable strings as it has states. The bound for did exactly that. Unlike the pumping lemma, this criterion never fails: if a language is nonregular, those distinguishable strings exist.
Minimization
The theorem establishes existence and uniqueness of the minimum DFA. We still need to calculate it from a given DFA. Two states of a DFA are distinguishable if some satisfies and , or the reverse, and equivalent () otherwise. If all states are reachable, says exactly that the prefixes reaching and lie in the same class. Merging equivalent states therefore yields the minimum DFA. Distinguishable pairs are found in rounds, from shortest distinguishing suffix to longest.
Proof
By induction on , a pair is marked in round if and only if its shortest distinguishing suffix has length . For this is the definition: distinguishes from exactly when one lies in and the other does not. For , if the shortest suffix is with , then distinguishes from and no shorter suffix does (if a shorter distinguished them, would distinguish from with length less than ). The induction hypothesis marks that successor pair in round , so is marked in round and not earlier, again by induction. Conversely, if is marked in round by symbol , its successor pair has a distinguishing suffix shorter than and distinguishes . There are finitely many pairs, so the rounds stop after at most markings.
∎For the DFA of remainders modulo 6 accepting , the pairs , and are never marked. and have the same remainder modulo 3, and since , the future value’s remainder modulo 3 depends only on the current remainder modulo 3. The algorithm rediscovers the automaton from the earlier section.
Three observations about the algorithm. First, remove unreachable states beforehand. The table does not identify them as redundant (in the example D is equivalent to F and would merge with it), but they do not correspond to any prefix and should be removed. Second, the naive cost is per round for up to rounds; working backwards from newly marked pairs reduces the total to , and Hopcroft’s partition-refinement algorithm (1971) reaches . Third, because the minimum DFA is unique, minimization gives a canonical form. Two regular expressions describe the same language if and only if their minimum DFAs are equal up to names, which can be checked by traversing them in parallel.
Beyond regular languages: the Chomsky hierarchy
The language is not regular (you will prove this in two ways in the exercises), but has an obvious finite description: the grammar with rule . A grammar has nonterminal symbols (here ), terminals (0 and 1), an initial symbol and rewriting rules . Its language consists of the terminal strings obtained from the initial symbol by applying rules. Chomsky (1956) classified grammars by the form of their rules. Each class corresponds exactly to a kind of machine:
| Type | Rules | Machine | Example | Membership |
|---|---|---|---|---|
| 3: regular | , , | finite automaton | linear time | |
| 2: context-free | pushdown automaton | , balanced parentheses, JSON | in general (CYK); linear for LL and LR subclasses | |
| 1: context-sensitive | , | linear bounded automaton | decidable, PSPACE-complete in general | |
| 0: unrestricted | Turing machine | the halting problem | semidecidable |
This is the Chomsky hierarchy, whose inclusions are strict. In a regular grammar, each rule generates one symbol and moves to a nonterminal playing the role of a state: is the arc . A pushdown automaton is an NFA with an unbounded stack. The stack is precisely the memory missing for : push one symbol for each 0 and pop one for each 1. Context-free grammars describe the syntax of nearly all programming languages and nested formats. Thus restricting decoding to JSON with a recursive schema needs a pushdown automaton rather than a finite automaton. A linear bounded automaton is a Turing machine restricted to the space occupied by its input. The Turing machine, unrestricted in memory or steps, is the subject of the next lesson: the Turing machine.
The table can be read in terms of memory. Regular languages need finite memory; context-free languages add a stack; context-sensitive languages use as much space as the input; and type 0 allows as much memory as needed. Each step buys expressive power at the cost of decision problems. For context-free grammars, deciding whether two generate the same language is already undecidable.
Real engines: backtracking and automata
The “regular expressions” in Perl, PCRE, Java, JavaScript, .NET and Python’s re module do not run as automata. They use a backtracking engine, a depth-first search that tries alternatives in order, tries quantifiers from more repetitions to fewer, and backtracks when a branch fails. It is easy to implement, supports precise capture semantics (“the first alternative that works”), and admits extensions no finite automaton can provide. Its cost depends on the number of ways to try matching a string, rather than the number of states.
With against , the engine must try every way to divide the occurrences of among repetitions of the outer quantifier before concluding that is missing. Those ways are the compositions of ; there are of them, because each of the gaps between letters either separates repetitions or does not. NFA simulation maintains a set of states and never backtracks. After any prefix with the set is the same, and the cost is per symbol.
(a+)+b the red curve is a line on a logarithmic scale with slope log 2, showing exponential growth. Compare (a|aa)*b, whose ratio between consecutive steps approaches the golden ratio; a*a*a*b, which is polynomial; the atomic group; and the same (a+)+b with an input that matches. Enter your own patterns: which ones grow explosively? Also try a backreference: the automaton refuses it for good reason.The common property of dangerous patterns is ambiguity: the NFA has many different paths reading the same string. In there are ; in there are as many as ways to write as an ordered sum of ones and twos, namely the Fibonacci number , which grows as with ; in there are , a polynomial number. When the string fails to match, a backtracking engine traverses all these paths; the automaton traverses them in parallel and never needs to count them. That is why the danger arises when the match fails or takes a long time to reach a successful branch. On matching input, the first branch can succeed immediately.
There is a second, fundamental difference. Backreferences such as \1 require exactly repeating a captured group and take these engines beyond regular languages. The pattern (a*)b\1 describes , which is not regular: the strings are pairwise distinguishable because is in the language while is not when . And (.+)\1 describes the “squares” . Matching with backreferences is NP-complete (Aho, 1990). Engines that guarantee linear time, such as RE2, Go’s regexp package and Rust’s regex crate, simply do not support them. They follow Russ Cox (2007), who brought back Thompson’s construction (1968): a Thompson NFA and simulation by sets of states. RE2 and Rust add a cached lazy DFA; Go uses simulation alone. The worst-case cost is for a pattern of size and text of size .
Detecting and mitigating ReDoS
For a system that accepts external text, defenses in decreasing order of robustness are:
- A linear-time engine for every pattern applied to untrusted inputs: RE2, a C++ library with bindings for Python and other languages; Go; Rust; or the
RegexOptions.NonBacktrackingoption in .NET 7. This defense does not depend on reviewing each pattern. - Unambiguous patterns. describes the same language as . A frequent real case is
(\w+\s?)*: when the space is missing, two consecutive repetitions of\w+compete for the same letters, just as in .(\w+(\s\w+)*\s?)?describes exactly the same language without ambiguity because every repetition must start with a space. With 22 letters and a final sign, the first takes around half a second inre; the second handles 100,000 letters in milliseconds. As a rule, a quantifier applied to something already containing a quantifier, or a star over alternatives that can read the same string, deserves scrutiny. - Cut off backtracking where the language remains unchanged. Since Python 3.11,
resupports atomic groups(?>...)and possessive quantifiers (a++,a*+), which do not reopen a closed repetition. They are not a general guarantee and change pattern meaning if placed incorrectly. - Resource limits on maximum input length (for a quadratic pattern, reducing 20,000 to 2,000 characters divides runtime by 100), maximum time per operation (the third-party
regexmodule supports atimeoutparameter), and isolation of the evaluating process. - Detection using static analyzers that search for ambiguity in the pattern’s NFA, and growth tests like those in the figure, with increasing input lengths that force failure, measuring CPU as well as results. This is what the Cloudflare case lacked.
Implementation from scratch
Start with a DFA represented as a dictionary, exhaustively check the invariant for multiples of 3, and construct the product automaton.
from itertools import product
def dfa_accepts(dfa, w):
q = dfa["start"]
for c in w:
q = dfa["delta"][q][c]
return q in dfa["accept"]
mod3 = {
"start": 0,
"accept": {0},
"delta": {r: {"0": (2 * r) % 3, "1": (2 * r + 1) % 3} for r in range(3)},
}
def val(w):
return int(w, 2) if w else 0
def strings(max_len, alphabet="01"):
for L in range(max_len + 1):
for t in product(alphabet, repeat=L):
yield "".join(t)
n_checked = 0
for w in strings(12):
q = mod3["start"]
for i, c in enumerate(w): # invariante: q == val(w[:i]) % 3 antes de leer w[i]
assert q == val(w[:i]) % 3
q = mod3["delta"][q][c]
assert (q in mod3["accept"]) == (val(w) % 3 == 0)
n_checked += 1
print(f"{n_checked} cadenas de longitud <= 12: el invariante y la aceptación se cumplen")
def product_dfa(A, B, op):
"""Autómata producto: estado (p, q); acepta según op(p en F_A, q en F_B)."""
start = (A["start"], B["start"])
delta, accept, todo, seen = {}, set(), [start], {start}
while todo:
p, q = s = todo.pop()
if op(p in A["accept"], q in B["accept"]):
accept.add(s)
delta[s] = {}
for c in "01":
t = (A["delta"][p][c], B["delta"][q][c])
delta[s][c] = t
if t not in seen:
seen.add(t)
todo.append(t)
return {"start": start, "accept": accept, "delta": delta}
par_unos = {"start": 0, "accept": {0}, "delta": {0: {"0": 0, "1": 1}, 1: {"0": 1, "1": 0}}}
ambos = product_dfa(mod3, par_unos, lambda a, b: a and b)
print("estados del producto:", len(ambos["delta"]))
assert all(dfa_accepts(ambos, w) == (val(w) % 3 == 0 and w.count("1") % 2 == 0) for w in strings(10))
print("intersección correcta en todas las cadenas de longitud <= 10")Next, implement a general NFA with transitions stored under the symbol "", and subset construction limited to reachable states. The family confirms the exponential growth.
import time
def closure(nfa, S):
"""ε-clausura: todo lo alcanzable desde S por transiciones ε (símbolo '')."""
S, todo = set(S), list(S)
while todo:
q = todo.pop()
for t in nfa["delta"].get((q, ""), ()):
if t not in S:
S.add(t)
todo.append(t)
return frozenset(S)
def subset_construction(nfa, alphabet="01"):
start = closure(nfa, {nfa["start"]})
delta, todo = {}, [start]
while todo:
S = todo.pop()
if S in delta:
continue
delta[S] = {}
for c in alphabet:
T = closure(nfa, {t for q in S for t in nfa["delta"].get((q, c), ())})
delta[S][c] = T
if T not in delta:
todo.append(T)
accept = {S for S in delta if S & nfa["accept"]}
return {"start": start, "accept": accept, "delta": delta}
def nth_from_end(n):
d = {(0, "0"): {0}, (0, "1"): {0, 1}}
for i in range(1, n):
d[(i, "0")] = d[(i, "1")] = {i + 1}
return {"start": 0, "accept": {n}, "delta": d}
for n in range(1, 13):
D = subset_construction(nth_from_end(n))
print(f"n = {n:2d}: NFA con {n + 1:2d} estados -> DFA con {len(D['delta']):5d} estados")
D = subset_construction(nth_from_end(4))
assert all(dfa_accepts(D, w) == (len(w) >= 4 and w[-4] == "1") for w in strings(9))
print("el DFA de n = 4 es correcto en todas las cadenas de longitud <= 9")With , an NFA with 13 states gives a DFA with 4,096. Next are regular expressions. The parser is recursive descent, with one function per precedence level, and produces a tree of tuples.
class Parser:
"""alt := cat ('|' cat)* cat := rep* rep := atom ('*' | '+' | '?')*
atom := '(' alt ')' | '.' | barra invertida + símbolo | símbolo"""
def __init__(self, src):
self.s, self.i = src, 0
def peek(self):
return self.s[self.i] if self.i < len(self.s) else None
def take(self):
c = self.peek()
self.i += 1
return c
def parse(self):
ast = self.alt()
if self.peek() is not None:
raise SyntaxError(f"sobra {self.peek()!r} en la posición {self.i}")
return ast
def alt(self):
node = self.cat()
while self.peek() == "|":
self.take()
node = ("alt", node, self.cat())
return node
def cat(self):
node = ("eps",)
while self.peek() not in (None, "|", ")"):
r = self.rep()
node = r if node == ("eps",) else ("cat", node, r)
return node
def rep(self):
node = self.atom()
while self.peek() in ("*", "+", "?"):
node = ({"*": "star", "+": "plus", "?": "opt"}[self.take()], node)
return node
def atom(self):
c = self.take()
if c == "(":
node = self.alt()
if self.take() != ")":
raise SyntaxError("falta ')'")
return node
if c == ".":
return ("any",)
if c == chr(92): # la barra invertida escapa el símbolo siguiente
return ("char", self.take())
if c in (None, ")", "*", "+", "?", "|"):
raise SyntaxError(f"símbolo inesperado {c!r} en la posición {self.i - 1}")
return ("char", c)
def parse(src):
return Parser(src).parse()
for r in ["ab|c", "(a|b)*abb", "a(b|)c?", "(a+)+b"]:
print(f"{r:10s} ->", parse(r))Thompson’s construction follows the four cases above. Each state has type char (one arc labeled by a symbol), any (one arc for any symbol), split (up to two arcs), or match (the end). A fragment’s final state is an split whose successors are filled in during composition. The code additionally adds an explicit match state at the end, one more than in the theoretical count. For star, it uses Russ Cox’s variant with the same two new states: the body’s end returns to entrance , which chooses another repetition or exit. This is correct because is reached only at the start or after a complete repetition, precisely the times when exit is allowed.
import re, random
class NFA:
"""kind[q] en {'char', 'any', 'split', 'match'}; out1 y out2 son los sucesores."""
def __init__(self):
self.kind, self.sym, self.out1, self.out2 = [], [], [], []
def new(self, kind, sym=None, out1=None, out2=None):
self.kind.append(kind); self.sym.append(sym); self.out1.append(out1); self.out2.append(out2)
return len(self.kind) - 1
def thompson(ast):
"""Devuelve (nfa, inicio). Cada fragmento tiene un estado de entrada y un estado final (un 'split'
sin sucesores) que se enlaza después: cada operador añade como mucho 2 estados."""
nfa = NFA()
def build(node):
op = node[0]
if op == "eps":
e = nfa.new("split")
return e, e
if op in ("char", "any"):
end = nfa.new("split")
s = nfa.new(op, node[1] if op == "char" else None, end)
return s, end
if op == "cat":
s1, e1 = build(node[1])
s2, e2 = build(node[2])
nfa.out1[e1] = s2 # arco ε del final del primero al inicio del segundo
return s1, e2
if op == "alt":
s1, e1 = build(node[1])
s2, e2 = build(node[2])
end = nfa.new("split")
nfa.out1[e1] = nfa.out1[e2] = end
return nfa.new("split", None, s1, s2), end
s1, e1 = build(node[1])
end = nfa.new("split")
if op == "star": # entrada: al cuerpo o fuera; el cuerpo vuelve a la entrada
s = nfa.new("split", None, s1, end)
nfa.out1[e1] = s
return s, end
if op == "plus": # el cuerpo al menos una vez
loop = nfa.new("split", None, s1, end)
nfa.out1[e1] = loop
return s1, end
if op == "opt":
nfa.out1[e1] = end
return nfa.new("split", None, s1, end), end
raise ValueError(op)
s, e = build(ast)
nfa.out1[e] = nfa.new("match")
return nfa, s
def eps_closure(nfa, states):
seen, todo = set(), list(states)
while todo:
q = todo.pop()
if q is None or q in seen:
continue
seen.add(q)
if nfa.kind[q] == "split":
todo.append(nfa.out1[q])
todo.append(nfa.out2[q])
return frozenset(seen)
def step(nfa, S, c):
return eps_closure(nfa, [nfa.out1[q] for q in S
if (nfa.kind[q] == "char" and nfa.sym[q] == c) or nfa.kind[q] == "any"])
class Regex:
def __init__(self, pattern):
self.pattern = pattern
self.nfa, self.start = thompson(parse(pattern))
self.match_state = len(self.nfa.kind) - 1
def fullmatch(self, s):
S = eps_closure(self.nfa, [self.start])
for c in s:
S = step(self.nfa, S, c)
if not S:
return False
return self.match_state in S
rnd = random.Random(0)
patrones = ["(a|b)*abb", "a(b|c)*d?", "(ab|a)*c", "(a+)+b", "((a|b)(a|b))*", "a?b+.c*", "(a|)(b|c)*"]
for p in patrones:
R, ref = Regex(p), re.compile(p)
for _ in range(2000):
s = "".join(rnd.choice("abcd") for _ in range(rnd.randrange(9)))
assert R.fullmatch(s) == bool(ref.fullmatch(s)), (p, s)
print(f"{p:14s} {len(R.nfa.kind):3d} estados 2000 cadenas al azar: mismo resultado que re")The seven patterns agree with re.fullmatch on all 14,000 strings. has 15 states: the 14 from the count ( symbols, two for union and two for star), plus match. Next is the lazy DFA: the same simulation, but each appearing set of states gets a number and each calculated transition is cached. After a few symbols, every step is a dictionary lookup.
import time
class LazyDFA(Regex):
"""Construcción de subconjuntos bajo demanda: cada conjunto de estados del NFA se guarda una vez
con un número, y cada transición se calcula la primera vez que hace falta."""
def __init__(self, pattern):
super().__init__(pattern)
self.ids, self.sets, self.trans = {}, [], {}
self.q0 = self._id(eps_closure(self.nfa, [self.start]))
def _id(self, S):
if S not in self.ids:
self.ids[S] = len(self.sets)
self.sets.append(S)
return self.ids[S]
def fullmatch(self, s):
q = self.q0
for c in s:
nxt = self.trans.get((q, c))
if nxt is None:
nxt = self.trans[(q, c)] = self._id(step(self.nfa, self.sets[q], c))
q = nxt
return self.match_state in self.sets[q]
rnd = random.Random(1)
texto = "".join(rnd.choice("ab") for _ in range(30000)) + "abb"
for Motor in (Regex, LazyDFA):
m = Motor("(a|b)*abb")
t = time.perf_counter()
r = m.fullmatch(texto)
print(f"{Motor.__name__:8s} resultado = {r} {time.perf_counter() - t:.3f} s")
print("estados del DFA construidos:", len(m.sets), " transiciones en caché:", len(m.trans))For 30,003 characters, the lazy DFA builds five states and nine transitions, and runs much faster than set simulation, which recomputes closure at every symbol. To minimize it, complete the lazy DFA by traversing all reachable states and apply table filling.
def full_dfa(motor, alphabet):
"""Completa el DFA perezoso recorriendo todo lo alcanzable."""
todo, seen = [motor.q0], {motor.q0}
while todo:
q = todo.pop()
for c in alphabet:
if (q, c) not in motor.trans:
motor.trans[(q, c)] = motor._id(step(motor.nfa, motor.sets[q], c))
t = motor.trans[(q, c)]
if t not in seen:
seen.add(t)
todo.append(t)
Q = sorted(seen)
delta = {(q, c): motor.trans[(q, c)] for q in Q for c in alphabet}
return Q, delta, {q for q in Q if motor.match_state in motor.sets[q]}
def minimize(Q, delta, F, alphabet):
"""Llenado de tabla hasta el punto fijo; devuelve el número de clases y el representante de cada estado."""
marked = {(p, q) for p in Q for q in Q if (p in F) != (q in F)}
changed = True
while changed:
changed = False
for p in Q:
for q in Q:
if p < q and (p, q) not in marked:
if any((delta[(p, c)], delta[(q, c)]) in marked for c in alphabet):
marked |= {(p, q), (q, p)}
changed = True
clase = {q: next(p for p in Q if p == q or (p, q) not in marked) for q in Q}
return len(set(clase.values())), clase
casos = [("(a|b)*abb", "ab"), ("(0|1)*1(0|1)(0|1)", "01"), ("(a|b)*a(a|b)(a|b)(a|b)(a|b)(a|b)", "ab"),
("(a|b)*", "ab"), ("(a*b*)*", "ab"), ("a*(ba*ba*)*", "ab")]
for p, alfabeto in casos:
Q, delta, F = full_dfa(LazyDFA(p), alfabeto)
k, _ = minimize(Q, delta, F, alfabeto)
print(f"{p:34s} DFA por subconjuntos: {len(Q):3d} estados mínimo: {k}")The minimum DFAs for and have 8 and 64 states, as the bound predicts. and have the same one-state minimum DFA: they are two expressions for the same language, as minimization proves. And , “an even number of ,” reduces to two states.
Finally, the ReDoS experiment uses real clocks: re.fullmatch versus our engine in on , stopping as soon as re takes more than a quarter of a second.
filas = []
for n in range(10, 31, 2):
s = "a" * n
t = time.perf_counter(); r1 = re.fullmatch("(a+)+b", s); t_re = time.perf_counter() - t
t = time.perf_counter(); r2 = LazyDFA("(a+)+b").fullmatch(s); t_propio = time.perf_counter() - t
assert bool(r1) == r2
filas.append((n, t_re, t_propio))
if t_re > 0.25:
break
for n, a, b in filas:
print(f"n = {n:2d} re: {a * 1e3:9.2f} ms motor propio (incluida la compilación): {b * 1e3:6.2f} ms")
print(f"cociente de tiempos de re entre n = {filas[-2][0]} y n = {filas[-1][0]}: {filas[-1][1] / filas[-2][1]:.1f}")
for p in ["(?>a+)+b", "(a++)+b", "a+b"]:
t = time.perf_counter(); re.fullmatch(p, "a" * 100000)
print(f"{p:9s} con n = 100000: {(time.perf_counter() - t) * 1e3:.2f} ms")re takes roughly four times as long for each additional pair of letters, as predicts, until the loop stops. Our engine’s time stays unchanged, dominated by compiling a nine-state NFA. The atomic group, possessive quantifier and non-nested rewrite handle in milliseconds.
The professional version
| Tool | Model | Guarantee | When |
|---|---|---|---|
re (Python), PCRE, Java, JavaScript | backtracking | none: exponential worst case | controlled patterns on trusted input; when backreferences are needed |
RE2 (pip install google-re2), Go regexp, Rust regex | Thompson NFA (RE2 and Rust add a lazy DFA) | any untrusted input | |
.NET with RegexOptions.NonBacktracking | automaton | linear | the same, in .NET |
regex (third-party Python) | backtracking | none, but supports timeout | when its extensions are needed |
lex, flex, re2c | compiled DFA | linear, without cache | lexical analyzers |
In Python, compile patterns once with re.compile, and distinguish fullmatch (the entire string, i.e. membership in the language), match (a prefix), and search (any substring). Python’s RE2 interface resembles re, so for patterns using only regular constructs the change takes one line:
import re2 # pip install google-re2
patron = re2.compile(r"(a+)+b")
patron.fullmatch("a" * 100_000) # tiempo lineal: devuelve None sin explorar ramas
If a pattern uses a backreference or assertion unsupported by RE2, compilation fails. A library promising linear time must make this distinction explicit.
Common mistakes
Exercises
More than one answer may be correct.
re, which of these patterns take exponential time in in the following full-match test? re.fullmatch(patron, 'a' * n + '!')More than one answer may be correct.
Step 1 of 4. Which string do you choose?
Step 1 of 3. Which family of strings do you propose?
Step 1 of 3. What is the base case?
nfa_accepts(nfa, s). The NFA is a dictionary with 'start' (a state), 'accept' (a set) and 'delta', which maps each (estado, símbolo) pair to a set of states. The symbol '' denotes ε transitions. Missing pairs have no transition. Return True if the NFA accepts string s. Take care with the empty string and ε-transition cycles.def nfa_accepts(nfa, s):
"""True si el NFA acepta s."""
current = {nfa["start"]}
for c in s:
nxt = set()
for q in current:
nxt |= nfa["delta"].get((q, c), set())
current = nxt
return bool(current & nfa["accept"])dfa_mod5(), returning the DFA in the lesson's format ('start', 'accept' and 'delta' with delta[q][c] for c in '01') for binary strings with divisible by 5 (with ), and minimize(dfa), returning an equivalent DFA with the minimum number of states using table filling after removing unreachable states. Tests compare every string up to length 16 with integer arithmetic and verify that minimize reduces a redundant DFA.def dfa_mod5():
"""DFA de los múltiplos de 5 en binario (estado = resto)."""
return {"start": 0, "accept": {0},
"delta": {r: {"0": (2 * r) % 3, "1": (2 * r + 1) % 3} for r in range(3)}}
def minimize(dfa):
"""Devuelve un DFA mínimo equivalente."""
return dfaSummary
- Design a DFA by deciding what each state remembers about the prefix, then prove it correct by induction over the input using that invariant. The product gives intersection and union, swapping accepting states gives complement, and reachability gives emptiness and equivalence.
- An NFA follows all hypotheses at once. The subset construction converts it to a DFA whose state is the active-state set and may inevitably require states, as for .
- Regular expressions, NFAs, and DFAs describe the same class of languages by Kleene’s theorem. Thompson’s construction yields a linear-size NFA, and the recurrence yields a regular expression.
- The pumping lemma, derived from the pigeonhole principle on states, can disprove regularity. Myhill-Nerode gives a characterization: is regular if and only if has finitely many classes. Their number is the size of the unique minimal DFA, computable by table filling.
- Above regular languages are context-free grammars with a stack, context-sensitive grammars, and Turing machines. Each level adds memory and loses decidable questions.
- Backtracking engines take time proportional to the number of possible matches, exponential for ambiguous patterns. Automaton-based engines such as RE2, Go, and Rust guarantee by forgoing backreferences. Use one when processing untrusted input.