এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
University Computer Science — Year 2 · স্নাতক দ্বিতীয় বর্ষ
22Regular Expressions and the Limits of Regular Languages
A search box accepts a pattern: (a|a)*b asks for some ’s, each written in one of two ways, then a . On a text of ’s with no , Python’s pattern engine answers “no match”. The program times that answer:
"""backtracking.py: Python's re on (a|a)*b against a^n, which has no b: time per n."""
import subprocess
import sys
PROGRAM = """
import re, time
pattern, text = re.compile("(a|a)*b"), "a" * {n}
t = time.perf_counter()
assert pattern.match(text) is None # every way of splitting is tried
print(time.perf_counter() - t)
"""
print(" n time (s) ratio to n - 1")
previous = None
for n in range(16, 28):
try: # each run in its own process, bounded
run = subprocess.run([sys.executable, "-c", PROGRAM.format(n=n)],
capture_output=True, text=True, timeout=60)
seconds = float(run.stdout)
except subprocess.TimeoutExpired:
print(f"{n:4} over 60 s: stopped")
break
ratio = f"{seconds / previous:6.2f}" if previous else ""
print(f"{n:4} {seconds:10.4f} {ratio}".rstrip())
previous = seconds
$ python backtracking.py
n time (s) ratio to n - 1
16 0.0033
17 0.0067 2.01
18 0.0130 1.96
19 0.0255 1.96
20 0.0574 2.25
21 0.1125 1.96
22 0.2097 1.86
23 0.4259 2.03
24 0.8915 2.09
25 1.7003 1.91
26 3.5214 2.07
27 6.6253 1.88
re on (a|a)*b and , on the laptop.Each extra doubles the time: 27 letters take more than six seconds, and a search box that receives such a pattern freezes. The pattern is not hard. It means the same as a*b, and the previous chapter’s automata decide it in one step per letter. This chapter connects the two: patterns, called regular expressions, describe exactly the languages that finite automata recognise; every automaton has a smallest equivalent one, which is unique; and some simple languages, such as balanced brackets, are beyond both. It ends with a pattern engine that cannot freeze.
You already know
Chapter 21: words, languages, concatenation and star ; deterministic automata (DFA), complete and trim; nondeterministic automata (NFA) with spontaneous transitions, which the subset construction turns into DFAs, at a cost of up to states; the product automaton, so that recognisable languages are closed under union, intersection and complement. The Year 1 volume: structural induction on trees, proving a property for leaves and then for each node from its children.
22.1 Regular expressions
Definition 22.1 (Regular expression, denoted language)
The regular expressions over an alphabet are the trees built by these rules: and are expressions, every letter is an expression, and if and are expressions, so are (alternation), (concatenation) and (star). The language denoted by an expression is defined on the tree: , , , , and . Two expressions are equivalent if they denote the same language.
Written on one line, star binds tighter than concatenation, which binds tighter than alternation: is . The size of an expression is the number of nodes of its tree. So denotes the words over that end with , and the words in which every is followed by a . The library of this chapter’s listings, regex.rs, holds the tree as a Rust enumeration with six cases, and its function lang is the definition run, cut at a length so that the sets stay finite:
/// The denotation, cut to the words of length at most n: the definition, run.
pub fn lang(re: &Re, n: usize) -> BTreeSet<String> {
match re {
Re::Empty => BTreeSet::new(),
Re::Eps => BTreeSet::from([String::new()]),
Re::Char(c) => if n >= 1 { BTreeSet::from([c.to_string()]) } else { BTreeSet::new() },
Re::Alt(x, y) => lang(x, n).union(&lang(y, n)).cloned().collect(),
Re::Cat(x, y) => {
let (lx, ly) = (lang(x, n), lang(y, n));
lx.iter().flat_map(|u| ly.iter().filter(move |v| u.len() + v.len() <= n)
.map(move |v| format!("{u}{v}"))).collect()
}
Re::Star(x) => {
let lx = lang(x, n);
let mut all = BTreeSet::from([String::new()]);
let mut frontier = all.clone();
while !frontier.is_empty() { // add one more factor until nothing new fits
let next: BTreeSet<String> = frontier.iter()
.flat_map(|u| lx.iter().filter(move |v| u.len() + v.len() <= n)
.map(move |v| format!("{u}{v}")))
.filter(|w| !all.contains(w)).collect();
all.extend(next.iter().cloned());
frontier = next;
}
all
}
}
}
It is slow, since it builds every word, but it is obviously right, and the tests check the fast code against it.
Definition 22.2 (Regular language)
A language is regular if some regular expression denotes it. Equivalently, the regular languages form the smallest class of languages that contains , and every , and is closed under union, concatenation and star.
The two descriptions agree by structural induction: every denoted language is in any such class, and the denoted languages form such a class. Every finite language is regular: is denoted by .
Definition 22.3 (Extended regular expression)
An extended regular expression also uses these abbreviations: a class [abc] for and a range [a-z] for every letter from a to z; for ; for ; and the counts for copies of followed by copies of , with .
Each abbreviation is an ordinary expression, so extended expressions denote regular languages too; but they can be much shorter: stands for an expression with 40 letters. The parser of regex.rs reads them by recursive descent, one function per priority level; the function for the postfix operators expands them on the spot:
fn parse_post(s: &[char], pos: &mut usize) -> Result<Re, String> {
let mut re = parse_atom(s, pos)?;
while *pos < s.len() {
re = match s[*pos] {
'*' => Re::Star(Box::new(re)),
'+' => Re::Cat(Box::new(re.clone()), Box::new(Re::Star(Box::new(re)))), // xx*
'?' => Re::Alt(Box::new(re), Box::new(Re::Eps)), // x|ε
'{' => {
let close = s[*pos..].iter().position(|&c| c == '}').ok_or("no '}'")? + *pos;
let body: String = s[*pos + 1..close].iter().collect();
let (m, n) = match body.split_once(',') {
Some((m, n)) => (m.parse(), n.parse()),
None => (body.parse(), body.parse()),
};
let bad = |_| "bad count";
let (m, n): (usize, usize) = (m.map_err(bad)?, n.map_err(bad)?);
*pos = close;
repeat(&re, m, n) // m copies, then n - m optional ones
}
_ => break,
};
*pos += 1;
}
Ok(re)
}
The syntax here is a small one. Practical pattern languages add a wildcard for any character, anchors for the start and end of a line, and often back-references, which ask a later part of the text to repeat what an earlier group matched. Back-references go beyond regular languages (Section 22.4); the other additions do not.
22.2 Kleene’s theorem
Expressions describe languages; automata recognise them. This section turns each into the other.
Method 22.4 (Thompson’s construction)
For each node of the expression’s tree, build an NFA fragment with spontaneous transitions, one entry state and one exit state , no transition into and none out of , by induction on the tree as drawn below:
- for : two states and no transition; for : ; for a letter: ;
- for : to the entry of , the exit of to the entry of , the exit of to , all spontaneous;
- for : spontaneous moves from to both entries and from both exits to ;
- for : spontaneous moves from to the entry of and to , and from the exit of back to its entry and to .
The fragment of the whole expression, with as start and as only accepting state, recognises . It has two states per node, for an expression of size , and at most two transitions leave each state.
Correctness is a structural induction: a path from to reads exactly a word of the subexpression’s language, since the only way out of a fragment is through its exit, which no transition leaves inside it. Thompson’s automaton is easy to build but full of spontaneous moves. Glushkov’s has none, and only one state per letter.
Definition 22.5 (Linear expression, local language)
An expression is linear if each letter occurs in it at most once. A language is local if there are sets and such that is the set of nonempty words whose first letter is in , whose last letter is in , and whose factors of length 2 are all in .
Whether a word belongs to a local language is decided by a window of two letters slid along it. Any expression is made linear by numbering its letters from the left, its positions: becomes . Erasing the numbers maps the linear expression’s language onto the original one.
Definition 22.6 (Glushkov automaton)
Let have positions , the letter at position being , and let be the linear expression. Define (whether ), (the positions that can begin a word of ), (those that can end one), and (the positions that can come right after in a word of ). The Glushkov automaton of has states , start state 0, transitions for and for , and accepting states , plus 0 if .
Method 22.7 (The Berry–Sethi computation)
Compute , and for every subexpression, bottom up: a position has ; for , ; an alternation takes the or and the unions; a concatenation has , , joined by if is nullable, and symmetrically for ; a star is nullable with its body’s sets. On the way, at each concatenation add to for every , and at each star add to for every .
The walk of regex.rs is this method, one case per kind of node:
/// Berry and Sethi: nullable, first and last of each subexpression, bottom up,
/// adding to follow at each concatenation and each star.
fn walk(re: &Re, g: &mut Glushkov) -> Sets {
let none = BTreeSet::new;
match re {
Re::Empty => (false, none(), none()),
Re::Eps => (true, none(), none()),
Re::Char(c) => {
g.letters.push(*c);
g.follow.push(none());
let j = g.letters.len(); // the next position
(false, BTreeSet::from([j]), BTreeSet::from([j]))
}
Re::Alt(x, y) => {
let ((nx, fx, lx), (ny, fy, ly)) = (walk(x, g), walk(y, g));
(nx || ny, &fx | &fy, &lx | &ly)
}
Re::Cat(x, y) => {
let ((nx, fx, lx), (ny, fy, ly)) = (walk(x, g), walk(y, g));
for &j in &lx {
g.follow[j].extend(fy.iter()); // the end of x, then the start of y
}
let first = if nx { &fx | &fy } else { fx };
let last = if ny { &lx | &ly } else { ly };
(nx && ny, first, last)
}
Re::Star(x) => {
let (_, fx, lx) = walk(x, g);
for &j in &lx {
g.follow[j].extend(fx.iter()); // the end of x, then x again
}
(true, fx, lx)
}
}
}
$ rustc --edition 2021 -O -o glushkov glushkov.rs && ./glushkov
positions: a1 b2 a3 b4 b5 nullable: false
first: {1, 2, 3} last: {5}
follow(1) = {1, 2, 3}
follow(2) = {1, 2, 3}
follow(3) = {4}
follow(4) = {5}
follow(5) = {}
511 of 511 words up to length 8 judged as the definition says
Proposition 22.8 (Glushkov’s automaton)
The Glushkov automaton of an expression with positions has states, no spontaneous transition, and at most transitions, and it recognises .
Proof. The counts come from the definition. For the language, first show by structural induction that is local with , and , and that the sets computed by Method 22.7 are these. For a position, both are clear. For , the positions of and are disjoint, no follow pair joins them, so a nonempty word passing the window test uses the positions of one side only and belongs to it. For , a word passing the test splits at the only pair with in and in , which the method added exactly for , ; the two parts pass the tests of and , or one part is empty and its side nullable. For , a word passing the test splits at the pairs with , added by the star, into words of ; and conversely every word of these languages passes the test. Finally, a run of the automaton on from 0 visits positions with , and each ; it accepts when (or and ). So the automaton accepts exactly when is the image of a word of the local language , that is, . ∎
Thompson’s automaton for has 20 states; Glushkov’s has 6:
$ rustc --edition 2021 -O -o thompson thompson.rs && ./thompson
expression Thompson states Glushkov states agree up to length 7
(a|b)*abb 20 6 true
a*b*c* 16 4 true
(ab|b)* 12 4 true
((a|b)(a|b))* 16 5 true
a?b?c 18 4 true
The way back, from an automaton to an expression, labels transitions with expressions and removes the states one by one.
Method 22.9 (State elimination)
Given an automaton with states , add a new start with the old start and a new end with for every accepting . Label each pair by an expression : the alternation of the letters from to , or . Then, for , remove state : for every pair of remaining states, replace
At the end only and remain, and denotes the language of the automaton.
The loop in dfa.rs, the second library of the chapter, is the formula of the method; the smart constructors cat, alt and star of regex.rs drop the and that would otherwise fill the result:
/// State elimination: edges labelled by expressions, a new start S and end E; remove
/// the states one by one, rerouting every path through the removed state.
pub fn eliminate(d: &Dfa) -> Re {
let n = d.delta.len();
let (s, e) = (n, n + 1);
let mut r = vec![vec![Re::Empty; n + 2]; n + 2];
for (q, row) in d.delta.iter().enumerate() {
for (a, &t) in row.iter().enumerate() {
r[q][t] = alt(r[q][t].clone(), Re::Char(d.alphabet[a]));
}
if d.accept[q] {
r[q][e] = Re::Eps;
}
}
r[s][0] = Re::Eps;
for k in 0..n {
let loop_k = star(r[k][k].clone());
for i in k + 1..n + 2 {
for j in k + 1..n + 2 {
let through = cat(cat(r[i][k].clone(), loop_k.clone()), r[k][j].clone());
r[i][j] = alt(r[i][j].clone(), through); // i -> k, loops on k, k -> j
}
}
}
r[s][e].clone()
}
$ rustc --edition 2021 -O -o eliminate eliminate.rs && ./eliminate
expression: 0*|0*1(10*1)*10*|0*1(10*1)*0(1|0(10*1)*0)*0(10*1)*10*
matches exactly the multiples of 3 among 0 .. 4095: true
Theorem 22.10 (Kleene’s theorem)
A language is regular if and only if it is recognisable by a finite automaton.
Proof. If , the Glushkov automaton recognises it (Proposition 22.8). Conversely, take an automaton and run Method 22.9. By induction on : after states are removed, denotes the set of words that lead from to through intermediate states among only. True for , where there is no intermediate state. A path from to through either avoids , and is counted by the old , or cuts at its visits to into a piece from to , any number of loops from to , and a piece from to , each avoiding inside: that is . At the end, denotes the words leading from to , which are the accepted words. ∎
With Chapter 21, regular languages are therefore closed under complement and intersection too, though expressions have no operator for either: the way goes through automata.
History
Stephen Kleene introduced regular expressions and proved the theorem in his paper of 1956 on nerve nets and finite automata. Victor Glushkov’s position automaton appeared in his 1961 survey of the theory of automata. Ken Thompson published his construction in 1968, in a short paper on searching text for a regular expression, where the NFA is simulated on all its states at once. Gérard Berry and Ravi Sethi showed in 1986 how to compute the positions’ sets on the expression directly, as in Method 22.7.
22.3 The minimal automaton
Many automata recognise the same language. What a DFA must remember after reading is what the rest of the word needs to know.
Definition 22.11 (Residual, Myhill–Nerode equivalence)
The residual (or left quotient) of a language by a word is . Two words are equivalent for , , if : no continuation tells them apart, .
For : , , , and . Every word has one of these three residuals.
Theorem 22.12 (Myhill–Nerode)
A language is recognisable if and only if it has finitely many residuals. Every complete DFA for has at least as many accessible states as has residuals, and the residual automaton reaches the bound: its states are the residuals, its start is , its transitions are , and its accepting states are the residuals that contain .
Proof. Let be a complete DFA for and the language it accepts from state . Then : is accepted exactly when leads to an accepting state (Proposition 21.5). So each residual is for some accessible , and there are at most as many residuals as accessible states. Conversely, suppose there are finitely many residuals. Since , the transitions of the residual automaton lead from a residual to a residual, and by induction on its run on from ends in . It accepts when , that is, when . ∎
Definition 22.13 (Minimal automaton)
A complete DFA for is minimal if no complete DFA for has fewer states. By the theorem, the residual automaton is minimal; it is called the minimal automaton of .
Corollary 22.14 (Uniqueness)
Every minimal complete DFA for equals the residual automaton up to the names of its states.
Proof. In a minimal DFA every state is accessible, or removing it would leave a smaller complete DFA. The map sends each state to a residual, reaches them all, and so is a bijection, since both sets have the same size. It respects the start (), the accepting states ( iff ) and the transitions (). ∎
Two states and of a DFA can be merged when . Moore’s method finds these pairs by looking further and further ahead.
Method 22.15 (Moore’s minimisation)
Start from an accessible complete DFA with states. Round 0 splits the states into two classes, accepting or not. Round puts and in the same class when they were in the same class at round and, for every letter , so were and . Stop at the first round that splits no class. Merging each final class into one state gives the minimal automaton.
Correctness. By induction on , and share a class at round exactly when no word of length at most is accepted from one and not from the other. A round that splits nothing gives the same partition at every later round, since a round depends only on the previous one; so the final classes are those of . Merging them gives a well defined DFA, since equivalent states have equivalent successors, with one state per residual of : the minimal automaton. Each round but the last adds a class, and there are at most , so there are at most rounds, each in time proportional to . ∎
/// Moore: start from {accepting, other}; split classes by the classes of the successors
/// until nothing splits. Returns the class of each state after each round.
pub fn moore(d: &Dfa) -> Vec<Vec<usize>> {
let renumber = |keys: Vec<Vec<usize>>| {
let mut seen = HashMap::new();
keys.into_iter().map(|k| {
let n = seen.len();
*seen.entry(k).or_insert(n) // a new key gets the next number
}).collect()
};
let first = d.accept.iter().map(|&a| vec![a as usize]).collect();
let mut rounds: Vec<Vec<usize>> = vec![renumber(first)];
loop {
let class = rounds.last().unwrap();
let keys = (0..d.delta.len())
.map(|q| {
let succ = d.delta[q].iter().map(|&r| class[r]);
std::iter::once(class[q]).chain(succ).collect() // own class, then successors'
})
.collect();
let next: Vec<usize> = renumber(keys);
let count = |c: &Vec<usize>| c.iter().max().map_or(0, |m| m + 1);
if count(&next) == count(class) {
return rounds; // stable: the classes are those of the minimal automaton
}
rounds.push(next);
}
}
The determinised Glushkov automaton of “starts with , or starts and ends with ” has 7 states; two rounds leave 4 classes:
$ rustc --edition 2021 -O -o minimise minimise.rs && ./minimise
state on a on b accepting
0 1 2 false
1 3 4 true
2 5 6 true
3 3 4 true
4 3 4 true
5 5 6 false
6 5 6 true
round 0: classes [0, 1, 1, 1, 1, 0, 1]
round 1: classes [0, 1, 2, 1, 1, 3, 2]
minimal automaton: 4 states, from 7
Moore’s method can need rounds, on an automaton shaped as a chain, and then costs time proportional to . John Hopcroft’s algorithm reaches : it keeps a list of splitters, a class and a letter, splits every class by “enters the splitter on that letter or not”, and when a class splits in two puts only the smaller half on the list. A state then joins a splitter at most times, since each time its class at least halves (Exercise 22.11).
22.4 The limits of regular languages
A finite automaton has a finite memory. A language that needs to count without bound is not regular.
Theorem 22.16 (Pumping lemma)
If is recognised by a DFA with states, every word with can be written with and , so that for every .
Proof. The run on the first letters of visits states, so one state appears twice, after reading and after reading , with and nonempty. Reading leads back to , so it can be read any number of times, zero included, and the run on ends where the run on ends, in an accepting state. ∎
Proposition 22.17 (Three languages that are not regular)
The languages , the balanced bracket words over , and the palindromes over are not regular.
Proof. For , by the pumping lemma: if a DFA with states recognised it, would split with , , since ; but is not in the language. Also by Theorem 22.12: for , is in the residual by and not in the residual by , so the residuals are infinitely many. Balanced brackets: their intersection with the regular language is , which is with other letters; if they were regular, so would be the intersection. Palindromes: for , is in the residual by and not in the residual by . ∎
The pumping lemma gives only a necessary condition: some languages that are not regular can be pumped. The residuals give the exact answer, and with them a proof is a matter of finding infinitely many words that pairwise differ in what must follow. A back-reference that repeats a group asks for the language , which has infinitely many residuals (by , as for palindromes); this is why pattern engines with back-references cannot be finite automata. Balanced brackets and arithmetic expressions need the grammars of Chapter 23.
History
The equivalence and the theorem carry the names of John Myhill and Anil Nerode; Nerode’s paper appeared in 1958. The pumping lemma for regular languages is a direct form of the pigeonhole argument used in its proof.
22.5 Deciding questions about automata
Because an automaton is a finite object, many questions about the infinite language it recognises can be answered by a program that always stops.
Proposition 22.18 (Questions and their costs)
For complete DFAs and with and states over :
- membership of a word : time proportional to ;
- emptiness, : no accepting state is accessible, a graph search in time proportional to ;
- finiteness: is infinite exactly when the trim automaton has a cycle, also a graph search;
- inclusion, : is empty, a search of the product in time proportional to ;
- equivalence: no accessible pair of the product has accepting and not, or the reverse; a breadth-first search finds a shortest word on which they differ, if there is one.
Proof. Membership is the run. Emptiness: a word is accepted exactly when its run reaches an accepting state, so is nonempty exactly when an accepting state is accessible. Finiteness: in the trim automaton every path extends into an accepted word; a cycle gives infinitely many paths, and without a cycle every path has fewer than transitions, so the accepted words are shorter than and finitely many. Inclusion is emptiness of the product for intersection with the complement (Proposition 21.17), and equivalence is two inclusions, read on the same product: the pair after is , and separates the languages exactly when one of the two states accepts and the other does not. ∎
From expressions, these questions go through automata. The Glushkov automaton is built in time proportional to and decides membership by simulation in at most steps; but inclusion and equivalence need complete DFAs, and determinisation may cost exponentially many states (Theorem 21.15). For short patterns it is fast:
$ rustc --edition 2021 -O -o equivalent equivalent.rs && ./equivalent
(a|b)* = (a*b*)*
(ab)*a = a(ba)*
a*b* differs from (a|b)*: on "ba"
(a|b)*abb differs from (a|b)*bb: on "bb"
(aa|a)* = a*
The witness "bb" is in the language of but does not end with . The checker itself is Exercise 22.9. By Corollary 22.14, a second way to compare is to minimise both automata and compare them state by state.
22.6 A pattern engine that cannot freeze
The engine of regex.rs parses the pattern into a tree, computes Glushkov’s sets, and simulates the automaton on sets of states, as Chapter 21 simulated NFAs. With at most 127 positions, a set of states is the bits of one 128-bit integer; for each letter, the next set is the union of the successors of the current states, kept only at positions holding that letter:
impl Matcher {
pub fn new(g: &Glushkov) -> Matcher {
assert!(g.letters.len() < 128, "at most 127 positions");
let bits = |s: &BTreeSet<usize>| s.iter().fold(0u128, |m, &j| m | 1 << j);
let mut succ = vec![bits(&g.first)];
succ.extend(g.follow[1..].iter().map(bits));
let mut with = std::collections::HashMap::new();
for (j, &c) in g.letters.iter().enumerate() {
*with.entry(c).or_insert(0) |= 1u128 << (j + 1);
}
Matcher { succ, with, accept: bits(&g.last) | g.nullable as u128 }
}
/// Accept or not, and the number of steps: at most m + 1 ORs per letter.
pub fn run(&self, word: &str) -> (bool, usize) {
let (mut set, mut steps) = (1u128, 0); // {0}
for c in word.chars() {
let mut next = 0;
let mut rest = set;
while rest != 0 {
next |= self.succ[rest.trailing_zeros() as usize];
rest &= rest - 1;
steps += 1;
}
set = next & self.with.get(&c).copied().unwrap_or(0);
}
(set & self.accept != 0, steps)
}
Proposition 22.19 (Linear matching)
On an expression with positions and a text of letters, the matcher performs at most unions, whatever the expression and the text.
Proof. Each letter costs one union per state of the current set, and the set holds at most the states. The set after letters is the set of states the Glushkov automaton can reach on the first letters, by induction on , so the answer is that of the automaton, which is correct by Proposition 22.8. ∎
On , with positions , , , the set after each is , and every letter costs two unions:
$ rustc --edition 2021 -O -o engine_compare engine_compare.rs && ./engine_compare
n matched steps steps/letter time (ms)
20 false 39 1.95 0.000
24 false 47 1.96 0.000
1000 false 1999 2.00 0.007
1000000 false 1999999 2.00 7.255
10000000 false 19999999 2.00 73.370
A backtracking engine tries one way to match at a time: on , each can be matched by the left or the right branch of , and when the missing makes a choice fail, the engine goes back to the last choice and tries the other. The ways to read all fail, and it tries them all. The automaton keeps every way at once, in a set that never holds more than states. Backtracking has reasons: it reports which part of the text each group matched, in the order a programmer expects, and it supports back-references, which no automaton can. Engines built on automata, in the line of Thompson’s, give up back-references and in exchange answer in linear time.
Facts as of 2026
Python’s re module is a backtracking engine. Since version 3.11 it offers possessive quantifiers such as a*+ and atomic groups, which throw away the backtracking points inside them and can stop a blow-up like the hook’s when the pattern’s author sees it coming. The POSIX standard defines basic and extended regular expressions for tools such as grep, and asks, when several matches start at the same point, for the longest.
On the town’s 24 street names, the engine answers patterns that expand to a hundred positions, since a range such as [A-Z] is an alternation of 26 letters:
// streets.rs: patterns over the town's street names.
#[allow(dead_code)]
mod regex;
fn main() {
let table = std::fs::read_to_string("../../../../data/town/streets.csv").unwrap();
let names: Vec<&str> = table.lines().skip(1)
.map(|line| line.split(',').nth(1).unwrap()).collect();
let patterns = ["[A-Z][a-z]* Road", "[A-Z][a-z]* (Road|Row|Way)",
"(Mill|River) [A-Za-z]*", "[A-Z][a-z]*(e|n) [A-Z][a-z]*",
"[A-Z][a-z]* [A-Z][a-z]*"];
for pattern in patterns {
let re = regex::parse(pattern).unwrap();
let g = regex::glushkov(&re);
let m = regex::Matcher::new(&g);
let hits: Vec<&str> = names.iter().copied().filter(|n| m.matches(n)).collect();
let some = hits.iter().take(2).copied().collect::<Vec<_>>().join(", ");
let (m, k) = (g.letters.len(), hits.len());
println!("{pattern:31} {m:3} positions {k:3} of {}: {some}", names.len());
}
}
$ rustc --edition 2021 -O -o streets streets.rs && ./streets
[A-Z][a-z]* Road 57 positions 4 of 24: Bridge Road, Castle Road
[A-Z][a-z]* (Road|Row|Way) 63 positions 14 of 24: Bridge Road, Bridge Way
(Mill|River) [A-Za-z]* 62 positions 5 of 24: Mill Avenue, Mill Row
[A-Z][a-z]*(e|n) [A-Z][a-z]* 107 positions 8 of 24: Bridge Road, Bridge Way
[A-Z][a-z]* [A-Z][a-z]* 105 positions 24 of 24: Bridge Road, Bridge Way
22.7 Exercises
Exercise 22.1 ★
Which of the words , , , , , , are in ? Describe the language in words, then check with the engine.
Solution
Solution of Exercise 22.1.
$ rustc --edition 2021 -O -o exo_match exo_match.rs && ./exo_match
"" true
"a" true
"aa" false
"bab" true
"abba" true
"babab" true
"aab" false
is the words in which every is immediately followed by a , and the final allows one more at the end. So , , , and match; and do not, since their first is followed by an .
Exercise 22.2 ★
A tool checks variable names with the pattern [a-z0-9_]+. Find the names it wrongly accepts, and write a pattern that requires a first character that is not a digit.
Solution
Solution of Exercise 22.2.
$ rustc --edition 2021 -O -o exo_ident exo_ident.rs && ./exo_ident
"x" [a-z0-9_]+ true [a-z_][a-z0-9_]* true
"x9" [a-z0-9_]+ true [a-z_][a-z0-9_]* true
"9lives" [a-z0-9_]+ true [a-z_][a-z0-9_]* false
"_tmp" [a-z0-9_]+ true [a-z_][a-z0-9_]* true
"2" [a-z0-9_]+ true [a-z_][a-z0-9_]* false
"" [a-z0-9_]+ false [a-z_][a-z0-9_]* false
[a-z0-9_]+ accepts 9lives and 2, which start with a digit. The pattern [a-z_][a-z0-9_]* asks for one letter or underscore, then any number of letters, digits or underscores: it rejects them, and still rejects the empty name.
Exercise 22.3 ★
Write an extended expression for the decimal numbers of Chapter 21’s hook (an optional sign, digits, an optional point followed by digits, an optional exponent). Check it against the hook’s automaton on every string of length at most 6 over the characters 0 1 + - . e E; in this chapter’s syntax, . is a plain letter.
Solution
Solution of Exercise 22.3.
$ rustc --edition 2021 -O -o exo_decimal exo_decimal.rs && ./exo_decimal
137257 strings, 1854 numbers, 0 disagreements
The expression is [+-]?[0-9]+(.[0-9]+)?([eE][+-]?[0-9]+)?: an optional sign, at least one digit, an optional group of a point and at least one digit, and an optional exponent with its own optional sign. It agrees with the automaton on all 137 257 strings of length at most 6 over the seven characters, 1 854 of which are numbers. A check on a finite set is not a proof; the proof is Exercise 22.9’s checker, run on the two automata.
Exercise 22.4 ★
Let be the number of words of length in . Find a recurrence for , and check it on .
Solution
Solution of Exercise 22.4.
$ rustc --edition 2021 -O -o exo_count exo_count.rs && ./exo_count
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233]
A nonempty word of the language starts either with , followed by any word of the language of length , or with , followed by one of length ; the two cases do not overlap, since the first letter tells them apart. So with : the Fibonacci numbers.
Exercise 22.5 ★★
Number the positions of and compute , , and every set by Method 22.7. Draw the Glushkov automaton.
Solution
Solution of Exercise 22.5.
$ rustc --edition 2021 -O -o exo_follow exo_follow.rs && ./exo_follow
a1 b2 a3 b4 a5; nullable false; first {1}; last {5}
follow(1) = {2, 4, 5}
follow(2) = {3}
follow(3) = {2, 4, 5}
follow(4) = {2, 4, 5}
follow(5) = {}
The star’s body has and ; the star adds to the follow sets of 3 and 4. The concatenation of with the star (nullable) gives , and the concatenation with adds 5 to the follow sets of 1, 3 and 4. Inside , . The automaton has states 0 to 5: ; from 1, 3 and 4: to 2, to 4 and to 5; ; state 5 accepts.
Exercise 22.6 ★★
A program minimises the incomplete DFA of (states 0, 1 after , 2 after , 3 accepting) by refining classes on the classes of the successors that exist, without completing it first. Which states does it merge, and which words does the merged automaton wrongly accept? How must the program be fixed?
Solution
Solution of Exercise 22.6.
$ rustc --edition 2021 -O -o exo_min_bug exo_min_bug.rs && ./exo_min_bug
classes: [0, 1, 1, 2]
ab: true
ba: true
aa: true
bb: true
States 1 and 2 both have one successor, in the accepting class, so the program merges them; it forgot that state 1 moves on and state 2 on . The merged automaton accepts and as well as and . The fix is to complete the automaton first, with a sink, and to compare the successors letter by letter, as in Listing 22.6: then 1 goes to the sink on and 2 goes to 3, and round 1 separates them.
Exercise 22.7 ★★
Apply Method 22.9 by hand to the two-state DFA of “an even number of ” over , removing the start state first. Check the expression on every word of length at most 10.
Solution
Solution of Exercise 22.7.
$ rustc --edition 2021 -O -o exo_eliminate exo_eliminate.rs && ./exo_eliminate
b*|b*a(b|ab*a)*ab*
right on all 2047 words up to length 10: true
eliminate, and its check.State 0 (even) is the start and accepts; , , , , with and . Removing 0 gives , , and . Removing 1 gives : no , or a first , blocks with an even number of , and a last .
Exercise 22.8 ★★
Prove that is not regular, once with the pumping lemma and once with residuals.
Solution
Solution of Exercise 22.8.
Let . Pumping: if a DFA with states recognised , then would split as with , so with , and would be in ; it is not, since . Residuals: for , is in but not in , so the words have pairwise different residuals, infinitely many, and Theorem 22.12 concludes.
Exercise 22.9 ★★
Write a function that takes two complete DFAs over the same alphabet and returns either “equivalent” or a shortest word on which they differ. Use it to compare expressions through their Glushkov automata.
Solution
Solution of Exercise 22.9.
/// None if the two automata recognise the same language, else a shortest word on which
/// they differ: a breadth-first search over the pairs of states.
pub fn difference(x: &Dfa, y: &Dfa) -> Option<String> {
let mut seen = HashMap::from([((0, 0), String::new())]);
let mut todo = VecDeque::from([(0, 0)]);
while let Some((p, q)) = todo.pop_front() {
let w = seen[&(p, q)].clone();
if x.accept[p] != y.accept[q] {
return Some(w);
}
for (a, &c) in x.alphabet.iter().enumerate() {
let next = (x.delta[p][a], y.delta[q][a]);
if let std::collections::hash_map::Entry::Vacant(e) = seen.entry(next) {
e.insert(format!("{w}{c}")); // a shortest word reaching this pair
todo.push_back(next);
}
}
}
None
}
The search starts from the pair of start states and follows each letter in both automata at once: this is the product automaton, built only as far as it is reached. Each pair is entered once, with the word that first reached it; since a breadth-first search reaches pairs in order of the length of that word, the first pair with different acceptance gives a shortest word on which the languages differ. If no such pair is reached, the languages are equal (Proposition 22.18). The cost is at most steps. Output 22.6 shows it on five pairs of expressions.
Exercise 22.10 ★★★
Show that is a right congruence: implies for every letter . Deduce that if is regular, the classes of are in bijection with the states of the minimal automaton, holding exactly when and lead it to the same state.
Solution
Solution of Exercise 22.10.
If , then , since iff iff . So is a right congruence. By definition, the classes of are in bijection with the residuals, by . By Corollary 22.14, the minimal automaton is the residual automaton, whose run on ends in (Theorem 22.12). So and lead it to the same state exactly when , that is, when , and the number of classes, the index of , is the number of states of the minimal automaton.
Exercise 22.11 ★★★
Implement Hopcroft’s algorithm: keep a list of splitters (a class and a letter); for a splitter , split each class into the states that enter on and the others; when a class splits, put both halves on the list if it was there, and otherwise only the smaller half. Check that it finds Moore’s classes, and compare the two on large automata. Why is the gain so small here?
Solution
Solution of Exercise 22.11.
let smaller = (0..blocks.len()).min_by_key(|&i| blocks[i].len()).unwrap();
let mut work: HashSet<(usize, usize)> = (0..k).map(|a| (smaller, a)).collect();
let mut hit = vec![false; n]; // marks, cleared after each splitter
while let Some(&(b, a)) = work.iter().next() {
work.remove(&(b, a));
let mut entering: Vec<usize> = blocks[b].iter() // the states entering b on a
.flat_map(|&q| inv[a][q].iter().copied()).collect();
entering.iter().for_each(|&p| hit[p] = true);
entering.sort_by_key(|&p| block_of[p]);
let mut touched: Vec<usize> = entering.iter().map(|&p| block_of[p]).collect();
touched.dedup();
for y in touched {
let (inside, outside): (Vec<usize>, Vec<usize>) =
blocks[y].iter().partition(|&&q| hit[q]);
if outside.is_empty() {
continue; // y lies entirely in the preimage: no split
}
let z = blocks.len(); // y keeps `inside`, the new block z gets `outside`
outside.iter().for_each(|&q| block_of[q] = z);
let small = if inside.len() <= outside.len() { y } else { z };
blocks[y] = inside;
blocks.push(outside);
for c in 0..k {
if work.contains(&(y, c)) {
work.insert((z, c)); // both halves still to be used
} else {
work.insert((small, c)); // the smaller half is enough
}
}
}
entering.iter().for_each(|&p| hit[p] = false);
}
$ rustc --edition 2021 -O -o minimise_bench minimise_bench.rs && ./minimise_bench
k DFA states minimal Moore rounds Moore (ms) Hopcroft (ms)
8 769 511 9 0.5 0.4
10 3073 2047 11 2.3 1.8
12 12289 8191 13 13.2 8.4
14 49153 32767 15 74.2 52.2
The predecessor lists inv let a splitter cost the number of transitions entering on . A state lies in a splitter on the list once per time its class is put there, and after its first time it is put there only as the smaller half, at most half of the previous class: at most times per letter. Summed over the states, the work is proportional to . The tests check that the classes are Moore’s on every sample. Here Hopcroft’s algorithm gains less than a factor of 2 (between 1.25 and 1.6 in the run printed): Moore’s method needs only rounds on these automata, about , so both do about work, and Hopcroft’s bookkeeping (a set of splitters, predecessor lists, sorting) costs more per step. On an automaton that is a chain of states, Moore needs about rounds and the difference becomes large.
Exercise 22.12 ★★★
Prove that is not regular, once with residuals and once by intersecting it with .
Solution
Solution of Exercise 22.12.
Let be the words with as many as . Residuals: for , and , so has infinitely many residuals. Intersection: , which is not regular (Proposition 22.17); since is regular and regular languages are closed under intersection, cannot be regular.
22.8 Problem: A search box that never freezes
Problem 22.1
Weekend problem — A search box that never freezes
The town’s website lets visitors search the street names with patterns. The first version used a backtracking engine, and a visitor froze it. This problem builds the replacement. The 24 names are Bridge Road, Bridge Way, Castle Road, Castle Row, Castle Way, Church Lane, Church Way, Garden Lane, Garden Road, Market Road, Market Row, Mill Avenue, Mill Row, Mill Street, Orchard Lane, Orchard Row, Orchard Way, River Avenue, River Lane, School Avenue, School Lane, School Way, Station Row and Willow Lane.
Part I — Patterns over the street names.
- How many names end in Road, in Row and in Way? Compare with Output 22.8.
- Why does
[A-Z][a-z]* Roadhave 57 positions? - Write a pattern for the names whose second word is Lane or Avenue. How many names does it match?
- List the 8 names matched by
[A-Z][a-z]*(e|n) [A-Z][a-z]*. - Show that any finite set of names is a regular language.
- A search box looks for the pattern anywhere in a name. Which expression, built from , denotes the names that contain a match of ?
Part II — The Glushkov engine.
Let over .
- Number the positions of and give , , and the follow sets.
- How many states and transitions does its Glushkov automaton have?
- Give the matcher’s set of states after each letter of . Is the word accepted, and how many unions were made?
- Show that after reading a letter, every state in the set is a position holding that letter.
- At most how many unions does the matcher make on a name of 12 letters with the pattern
[A-Z][a-z]* Road? - Why does the matcher refuse patterns with more than 127 positions, and how would you lift the limit?
Part III — One automaton per language.
- Determinise the Glushkov automaton of over , with the empty set as sink. How many states?
- Apply Moore’s method to it. How many rounds, and how many classes at the end?
- List the residuals of , and match them with the final classes.
- Show that and are equivalent.
- Find a shortest word on which and differ.
- The site stores compiled patterns in a cache. Why can two patterns that denote the same language share one entry, and how can a key be computed for it?
Part IV — Backtracking against the automaton.
- In how many ways can be read as a sequence of matches of ?
- Why does a backtracking engine try all of them on ? Relate this to the ratios of Output 22.1.
- From the hook’s last line, estimate how long the old site would take for 40 letters.
- How many unions does the matcher make on with ? Check with Output 22.7.
- How long does the matcher take for 40 letters, and for ten million?
- State the result: from exponential to linear, backtracking’s time doubling with each , measured, against at most steps proved for the automaton.
Solution
Solution of Problem 22.1.
1. 4 end in Road, 5 in Row and 5 in Way: the 14 of the second line.
2. [A-Z] is an alternation of 26 letters, [a-z]* the star of 26 more, then the space and the four letters of Road: .
3. [A-Z][a-z]* (Lane|Avenue): the 6 lanes and the 3 avenues, 9 names.
4. Bridge Road, Bridge Way, Castle Road, Castle Row, Castle Way, Garden Lane, Garden Road, Station Row.
5. The alternation of the names, each written as a concatenation of its letters, denotes the set.
6. , with written as a class of every character that can occur in a name.
7. ; is false, , , , , .
8. 5 states, and transitions.
9. : accepted, after 5 unions, one per letter, since each set holds one state.
10. The next set is masked by the positions holding the letter just read; equivalently, every transition into a position carries that position’s letter.
11. At most (Proposition 22.19).
12. A set of states is the bits of one 128-bit integer, state 0 included. With a vector of 64-bit words as the set, a union costs one OR per word, in all.
13. Six states: ; , and , reached by , and ; , reached from by ; and the sink . and have the transitions of .
14. Round 0: against the rest. Round 1: , and go to on , the others do not: three classes. Round 2: goes to on , to , which are now in different classes: four classes. Round 3 splits nothing. The minimal automaton has 4 states.
15. (by , , , …), (by ), (by ) and (by , , …): the classes , , and .
16. Both denote the words over in which every is immediately followed by a , then . Such a word is a block of ’s, then blocks starting with followed by ’s, which is ; and every word of has each followed by . The checker of Exercise 22.9 confirms it.
17. : it is in the first language and lacks the before in the second. No shorter word differs, since , and are in neither.
18. By Corollary 22.14, patterns with the same language have the same minimal automaton up to the names of the states. Renumbering its states in the order a breadth-first search from the start meets them, letters in a fixed order, makes the transition table and the accepting states a canonical key.
19. : each is read by the left or the right branch.
20. Every way reaches the end of the text without a and fails; the engine then returns to its last choice and tries the other branch, so it tries all . One more doubles the ways, and the measured ratios are close to 2.
21. About s, 15 hours.
22. One union for the first letter, from , then two for each later one, from : , as the output shows (39 for 20 letters, 1 999 for 1 000).
23. About 7.3 ns a letter: some 0.3 s for 40 letters, and 73 ms for ten million.
24. From exponential to linear: on and , the backtracking engine’s time doubles with each , as measured, reaching 6.6 s at ; the Glushkov matcher makes at most unions on any pattern of positions and any text of letters, as proved, here , and answers ten million letters in 73 ms.