Skip to main content

01 - Regular Expressions and Regular Languages

What a regular expression denotes, how to check it with a program, and where the pumping lemma and Myhill-Nerode show its limit.

What do you think about this article?

01 - Regular Expressions and Regular Languages
Formal Languages & Compilersfedericocalo.dev

At a Glance

What a regular expression denotes, how to check it with a program, and where the pumping lemma and Myhill-Nerode show its limit.

A text field must accept "three-letter codes followed by digits" and reject everything else: you write a pattern, try it on four examples, and it works. Then a string arrives that you had not foreseen, and you cannot tell whether the pattern is wrong or whether your idea of "everything else" was vague. A regular expression is a precise way of describing a set of strings, a language, using just three operations. This article gives you the definition, shows you how to check it with a program instead of trusting intuition, and tells you where its power ends: counting, for instance, is out of reach.

It is the first of six articles in the Formal Languages and Compilers series. You need no prerequisites beyond a little Python and the notion of a set; every theoretical result comes with a program that puts it to the test. I ran the listings with Python 3.14.4, and every output shown is identical across two consecutive runs.

What a regular expression denotes

Fix an alphabet Σ, that is, a finite set of symbols, for example {a, b}. A string is a finite sequence of symbols, and ε is the empty string. Regular expressions are built from the symbols of the alphabet, from ε and from three operations, and each one denotes a language, that is, a set of strings. The language L(R) is defined by induction on the form of R.

  • L(a) = {a} for every symbol a, and L(ε) = {ε};
  • L(R|S) = L(R) ∪ L(S): the string is fine if it is fine for one or the other;
  • L(RS) = {xy : x ∈ L(R), y ∈ L(S)}: a string of R followed by one of S;
  • L(R*) = ∪ L(R)n for n ≥ 0: zero or more strings of R one after the other, so always ε as well.

The three operations are not on an equal footing: under the usual conventions the star binds tighter than concatenation, which binds tighter than alternation, so ab*|c means (a(b*))|c and not (ab)*|c. A concrete example: (a|b)*abb describes all the strings over {a, b} that end with abb. It accepts abb, aabb, babb; it rejects ab and bba, which do not end with that sequence. The empty language ∅ is an expression in its own right in the formal definitions, but it has no syntax in practical engines and we will not use it here.

Inductive definitions read like programs. The first listing, regex_ast.py, contains two functions: parse, a recursive-descent parser with one function per precedence level (alt, cat, star, atom), and lang, which computes the words of L(R) of length at most n by applying the four rules above to the letter. In the star, the while frontier loop adds the new concatenations at each turn and stops by itself, because the bound n makes the set of candidates finite; ε is discarded from base because concatenating it produces no new words.

# regex_ast.py - regular expression parser and "by definition" semantics
def parse(expr):
    pos = 0

    def peek():
        return expr[pos] if pos < len(expr) else None

    def alt():                      # lowest level: R|S
        nonlocal pos
        node = cat()
        while peek() == '|':
            pos += 1
            node = ('alt', node, cat())
        return node

    def cat():                      # concatenation: RS
        node = None
        while peek() is not None and peek() not in '|)':
            f = star()
            node = f if node is None else ('cat', node, f)
        return ('eps',) if node is None else node

    def star():                     # highest level: R*
        nonlocal pos
        node = atom()
        while peek() == '*':
            pos += 1
            node = ('star', node)
        return node

    def atom():
        nonlocal pos
        c = peek()
        if c == '(':
            pos += 1
            node = alt()
            if peek() != ')':
                raise ValueError('missing closing parenthesis')
            pos += 1
            return node
        if c is None or c in '|)*':
            raise ValueError(f'unexpected symbol at position {pos}')
        pos += 1
        return ('char', c)

    node = alt()
    if pos != len(expr):
        raise ValueError('closing parenthesis without opening one')
    return node


def lang(node, n):
    """The words of L(node) of length at most n, computed from the definition."""
    kind = node[0]
    if kind == 'eps':
        return {''}
    if kind == 'char':
        return {node[1]} if n >= 1 else set()
    if kind == 'alt':
        return lang(node[1], n) | lang(node[2], n)
    if kind == 'cat':
        left, right = lang(node[1], n), lang(node[2], n)
        return {x + y for x in left for y in right if len(x) + len(y) <= n}
    base = lang(node[1], n) - {''}          # kind == 'star'
    result, frontier = {''}, {''}
    while frontier:
        frontier = {x + y for x in frontier for y in base
                    if len(x) + len(y) <= n} - result
        result |= frontier
    return result

The file prints nothing: it is a library, and its correctness is measured in the next program. The second check is independent of the first, because it uses the re module of Python's standard library, which implements regular expressions with an engine different from mine, and whose fullmatch requires the whole string to belong to the language (documentation of the re module). For each expression I enumerate all the strings over the alphabet up to length 8 and compare the set that comes out of the definition with the one accepted by re. In the last line I also check a formula: the strings of length n that end with abb number 2n-3, because the first n-3 positions are free.

# confronto.py - the definition of L(R) against the re module, on all strings
import re
from itertools import product
from regex_ast import parse, lang

N = 8

def tutte(alfabeto, n):
    return [''.join(t) for k in range(n + 1) for t in product(alfabeto, repeat=k)]

casi = [('(a|b)*abb', 'ab'), ('(a|b)*a(a|b)', 'ab'), ('(0|1)*01(0|1)*', '01'),
        ('(ab|a)*', 'ab'), ('((a*)*b*)*', 'ab'), ('a(b|())*', 'ab')]
for espr, alfabeto in casi:
    per_definizione = lang(parse(espr), N)
    con_re = {w for w in tutte(alfabeto, N) if re.fullmatch(espr, w)}
    print(f'{espr:16} words={len(per_definizione):3}  equal to re: {per_definizione == con_re}')

lunghezze = [sum(1 for w in lang(parse('(a|b)*abb'), 10) if len(w) == n) for n in range(3, 11)]
print('(a|b)*abb, lengths 3..10:', lunghezze, '== 2^(n-3):', lunghezze == [2 ** (n - 3) for n in range(3, 11)])

# Output:
# (a|b)*abb        words= 63  equal to re: True
# (a|b)*a(a|b)     words=254  equal to re: True
# (0|1)*01(0|1)*   words=466  equal to re: True
# (ab|a)*          words= 88  equal to re: True
# ((a*)*b*)*       words=511  equal to re: True
# a(b|())*         words=  8  equal to re: True
# (a|b)*abb, lengths 3..10: [1, 2, 4, 8, 16, 32, 64, 128] == 2^(n-3): True

On six expressions, including the awkward ((a*)*b*)*, which accepts all 511 strings up to length 8, the definition and re coincide. This does not prove that my lang is correct for every expression: it shows that on these cases and on this finite set there is no disagreement, which is the same kind of guarantee a test suite gives you. It is worth remembering when, later on, I use enumeration to "verify" an equality: an enumeration finds counterexamples, a proof rules them all out.

When two expressions say the same thing

Two expressions are equivalent if they denote the same language. Equivalences are used for simplification: an engine or a linter that rewrites (a*)* as a* saves work for the matcher. The four you will use most often are all proved with the same technique, double inclusion.

Take (R*)* = R*. If w ∈ L((R*)*), then w = u1…uk with each ui ∈ L(R*), and each of these is in turn a concatenation of words of L(R): putting everything in a row, w is a concatenation of words of L(R), hence it is in L(R*). In the other direction, L(R*) ⊆ L((R*)*) because every language is contained in its own Kleene closure (just take k = 1). No induction on n is needed: the structure of the definition does all the work.

The program identita.py tries eight pairs. The first five are true identities, among them (a|b)* = (a*b*)* and the sliding rule (ab)*a = a(ba)*; the last three are mistakes people really make, for instance believing that (a|b)* and a*b* are the same thing. For each false pair the program prints the shortest witness, that is, the shortest string that one expression accepts and the other does not.

# identita.py - equalities between expressions, checked up to length 9
from regex_ast import parse, lang

N = 9
coppie = [('(a*)*', 'a*'), ('a|a', 'a'), ('a(b|c)', 'ab|ac'),
          ('(a|b)*', '(a*b*)*'), ('(ab)*a', 'a(ba)*'),      # the first five hold
          ('(a|b)*', 'a*b*'), ('(ab)*', 'a*b*'), ('(a|b)*', '(ab)*')]   # the last three do not
for r, s in coppie:
    lr, ls = lang(parse(r), N), lang(parse(s), N)
    if lr == ls:
        print(f'{r:9} = {s:9} up to n={N}  ({len(lr)} words)')
    else:
        testimone = min(lr ^ ls, key=lambda w: (len(w), w))
        dentro = 'the first' if testimone in lr else 'the second'
        print(f'{r:9} != {s:9} witness {testimone!r}, accepted by {dentro}')

# Output:
# (a*)*     = a*        up to n=9  (10 words)
# a|a       = a         up to n=9  (1 words)
# a(b|c)    = ab|ac     up to n=9  (2 words)
# (a|b)*    = (a*b*)*   up to n=9  (1023 words)
# (ab)*a    = a(ba)*    up to n=9  (5 words)
# (a|b)*    != a*b*      witness 'ba', accepted by the first
# (ab)*     != a*b*      witness 'a', accepted by the second
# (a|b)*    != (ab)*     witness 'a', accepted by the first

The five identities hold up to length 9 (a check, not a proof: the proofs are the ones by double inclusion). The three false ones are refuted at once: ba belongs to (a|b)* but not to a*b*, which wants all the as before the bs. A short witness is the quickest way to fix a pattern: when two expressions that should coincide do not, first look for the shortest string on which they disagree and see which of the two is wrong.

Regular languages and Kleene's theorem

A language is regular if it is denoted by some regular expression. Kleene's theorem says that this class coincides with the class of languages accepted by a finite-state automaton, deterministic (DFA) or not (NFA): three ways of saying the same thing. "Finite memory" means that the automaton, while reading, remembers only which of a fixed number of states it is in: it cannot count up to a number chosen by the input. In the Chomsky hierarchy, whose starting point is "Three models for the description of language" (1956), regular languages are the lowest level (I verified the metadata of that publication on Crossref, but I have not read the text).

The theorem has two directions, and each is an algorithm. From expression to automaton you go with Thompson's construction, described in "Regular expression search algorithm" (Communications of the ACM, 11, June 1968; I read only the metadata on Crossref, not the article), which I build in the second article. From automaton to expression you go by state elimination, and we do that here.

The idea: in the automaton put the expressions on the edges, add an initial state I and a final state F, then remove one internal state q at a time. For each pair (p to q, q to t) you create or extend the edge p → t with a · (loop of q)* · b, where a and b are the expressions of the two edges. When only I and F remain, the expression on the edge joining them is the one you are after. In the listing, unisci builds the alternatives, stella adds parentheses only when needed, and '' represents ε. The program eliminates the states in all 24 possible orders.

# eliminazione.py - from DFA to regular expression, by state elimination
import re
from itertools import permutations, product

def unisci(x, y):
    if x is None: return y
    if y is None: return x
    return x if x == y else f'({x}|{y})'

def conc(x, y):
    return None if x is None or y is None else x + y

def stella(r):
    if r == '': return ''
    return r + '*' if len(r) == 1 else f'({r})*'

def a_regex(stati, delta, inizio, accetti, ordine):
    archi = {}
    for (p, c), q in delta.items():
        archi[(p, q)] = unisci(archi.get((p, q)), c)
    archi[('I', inizio)] = ''                       # '' is epsilon
    for s in accetti:
        archi[(s, 'F')] = unisci(archi.get((s, 'F')), '')
    for q in ordine:
        ciclo = archi.pop((q, q), None)
        mezzo = '' if ciclo is None else stella(ciclo)
        dentro = {p: r for (p, x), r in archi.items() if x == q}
        fuori = {t: r for (x, t), r in archi.items() if x == q}
        for chiave in [k for k in archi if q in k]:
            del archi[chiave]
        for p, a in dentro.items():
            for t, b in fuori.items():
                archi[(p, t)] = unisci(archi.get((p, t)), conc(conc(a, mezzo), b))
    return archi.get(('I', 'F'))

def simula(delta, inizio, accetti, w):
    s = inizio
    for c in w:
        s = delta[(s, c)]
    return s in accetti

stati = ['q0', 'q1', 'q2', 'q3']                    # DFA of (a|b)*abb
delta = {('q0', 'a'): 'q1', ('q0', 'b'): 'q0', ('q1', 'a'): 'q1', ('q1', 'b'): 'q2',
         ('q2', 'a'): 'q1', ('q2', 'b'): 'q3', ('q3', 'a'): 'q1', ('q3', 'b'): 'q0'}
stringhe = [''.join(t) for k in range(10) for t in product('ab', repeat=k)]
lunghezze, errori = [], 0
for ordine in permutations(stati):
    r = a_regex(stati, delta, 'q0', {'q3'}, ordine)
    lunghezze.append(len(r))
    errori += sum(bool(re.fullmatch(r, w)) != simula(delta, 'q0', {'q3'}, w) for w in stringhe)
print('orders tried:', len(lunghezze), ' minimum/maximum length:', min(lunghezze), max(lunghezze))
print('disagreements with the DFA simulation:', errori, 'out of', len(lunghezze) * len(stringhe))
print('order q0,q1,q2,q3:', a_regex(stati, delta, 'q0', {'q3'}, stati))

# Output:
# orders tried: 24  minimum/maximum length: 26 62
# disagreements with the DFA simulation: 0 out of 24552
# order q0,q1,q2,q3: b*aa*b(aa*b)*b((a|bb*a)a*b(aa*b)*b)*

The second check here is the simulation of the DFA: for each of the 24 orders and each of the 1023 strings up to length 9, the expression found and the automaton give the same answer (24,552 comparisons, zero disagreements). The result that does not show in the formulas but can be measured is another one: the same four-state automaton produces expressions from 26 to 62 characters long depending on the elimination order, and the one for the natural order, b*aa*b(aa*b)*b((a|bb*a)a*b(aa*b)*b)*, is much longer than the 9 letters of (a|b)*abb we started from. I do not prove a general bound on the size of the expression here: the measurement only says that the order matters and that the result, even if correct, is far from what you would write by hand.

What you can do with regular languages: closures

A class of languages is closed under an operation if applying it to languages of the class keeps you inside the class. For regular languages the operations that preserve regularity are many, and the construction that realizes them says how a compiler might implement them.

  • union, concatenation and star: they are the very operations of regular expressions, so by definition;
  • intersection and difference: with the product automaton, which reads the string with two automata in parallel;
  • complement: final and non-final states are swapped, but only in a total DFA (with one transition for every state-symbol pair);
  • reversal (the string read backwards) and image under a homomorphism (replacing each symbol with a string): they are proved on the NFA or on the expression.

The items can be reordered without changing the meaning; the distinction that matters is the one inside the third. The complement of an NFA is not obtained by swapping the final states, because an NFA accepts when an accepting path exists, and negating "exists" requires considering all the paths: you must determinize first, and determinization can make the states grow (we measure it in article 02).

In the product of M1 and M2 the states are the pairs, δ((p, q), c) = (δ1(p, c), δ2(q, c)), and only the set of final states changes from one operation to the other: pairs with both final for the intersection, at least one for the union, the first yes and the second no for the difference. The listing implements this with a function combina passed to prodotto. It uses two automata of two states each, which count the parity of the as and that of the bs, and checks each operation on 2047 strings against a Python predicate written directly on the definition.

# dfa.py - total deterministic automata, product and complement
from itertools import product

class DFA:
    def __init__(self, alfabeto, delta, inizio, accetti):
        self.alfabeto, self.delta = alfabeto, delta
        self.inizio, self.accetti = inizio, frozenset(accetti)
        self.stati = sorted({s for (s, _) in delta}, key=repr)

    def accetta(self, w):
        s = self.inizio
        for c in w:
            s = self.delta[(s, c)]
        return s in self.accetti

def prodotto(a, b, combina):
    delta = {((p, q), c): (a.delta[(p, c)], b.delta[(q, c)])
             for p in a.stati for q in b.stati for c in a.alfabeto}
    accetti = {(p, q) for p in a.stati for q in b.stati
               if combina(p in a.accetti, q in b.accetti)}
    return DFA(a.alfabeto, delta, (a.inizio, b.inizio), accetti)

def complemento(a):
    return DFA(a.alfabeto, a.delta, a.inizio, set(a.stati) - a.accetti)

def parita(simbolo):
    delta = {(p, c): (1 - p if c == simbolo else p) for p in (0, 1) for c in 'ab'}
    return DFA('ab', delta, 0, {0})

pari_a, pari_b = parita('a'), parita('b')
tutte = [''.join(t) for k in range(11) for t in product('ab', repeat=k)]
prove = {
    'intersection': (prodotto(pari_a, pari_b, lambda x, y: x and y),
                     lambda w: w.count('a') % 2 == 0 and w.count('b') % 2 == 0),
    'union':        (prodotto(pari_a, pari_b, lambda x, y: x or y),
                     lambda w: w.count('a') % 2 == 0 or w.count('b') % 2 == 0),
    'difference':   (prodotto(pari_a, pari_b, lambda x, y: x and not y),
                     lambda w: w.count('a') % 2 == 0 and w.count('b') % 2 == 1),
    'complement':   (complemento(pari_a), lambda w: w.count('a') % 2 == 1),
}
for nome, (automa, predicato) in prove.items():
    errori = sum(automa.accetta(w) != predicato(w) for w in tutte)
    print(f'{nome:13} states={len(automa.stati)}  strings tried={len(tutte)}  errors={errori}')
print('accepted by the intersection:', [w for w in ('aabb', 'baab', 'abab', 'ab', 'aab')
                                      if prove['intersection'][0].accetta(w)])

# Output:
# intersection  states=4  strings tried=2047  errors=0
# union         states=4  strings tried=2047  errors=0
# difference    states=4  strings tried=2047  errors=0
# complement    states=2  strings tried=2047  errors=0
# accepted by the intersection: ['aabb', 'baab', 'abab']

Four states for the two-automaton operations, two for the complement, zero errors on 2047 strings. The states of the product are |Q1|·|Q2| in the general case: with two automata of two states that is little, with two of a thousand states it is a million, and it pays to build only the pairs reachable from the initial state.

The pumping lemma: how to prove that a language is not regular

The lemma says: if L is regular there is a length p ≥ 1 such that every word w ∈ L with |w| ≥ p can be written w = xyz with three properties: |y| ≥ 1, |xy| ≤ p, and xyiz ∈ L for every i ≥ 0. The proof is the pigeonhole argument: take a DFA with p states for L. A word at least p long passes through p+1 states in the first p steps, so one repeats; the part read between the two visits is y, and you can run that cycle zero, one or a hundred times without changing the outcome.

The lemma is used by contraposition. To show that L = {anbn : n ≥ 0} is not regular, suppose for contradiction that it is, with length p, and choose w = apbp. Since |xy| ≤ p, y is made of as only, say y = ak with k ≥ 1; then xy2z = ap+kbp has more as than bs and is not in L. The delicate point is that the choice of w is yours, while the decomposition is chosen by the adversary: you must show that every decomposition fails.

The program pumping.py does all this with numbers, in four parts. The first tries every decomposition of apbp for p from 1 to 8. The second checks the lemma from the right side: for (a|b)*abb, which has a DFA with 4 states, it looks for each sufficiently long word a decomposition that can be pumped. The third counts the Myhill-Nerode classes, and the fourth shows a non-regular language that the lemma does not manage to rule out.

# pumping.py - the lemma on regular languages, and Myhill-Nerode, with numbers
import re
from itertools import product

def in_L(w):                                  # L = { a^n b^n : n >= 0 }
    n = w.count('a')
    return w == 'a' * n + 'b' * n

print('Part 1: a^p b^p, every decomposition xyz with |xy| <= p, |y| >= 1')
for p in range(1, 9):
    w = 'a' * p + 'b' * p
    scomposizioni = [(w[:i], w[i:j], w[j:]) for j in range(1, p + 1) for i in range(j)]
    reggono = [(x, y, z) for x, y, z in scomposizioni
               if all(in_L(x + y * k + z) for k in range(4))]
    print(f'  p={p}: decompositions={len(scomposizioni):2}  that stay in L for i=0..3: {len(reggono)}')

print('Part 2: (a|b)*abb, which has a DFA with 4 states, so p = 4')
def reg(w):
    return re.fullmatch('(a|b)*abb', w) is not None
controllate = riuscite = 0
for n in range(4, 11):
    for t in product('ab', repeat=n):
        w = ''.join(t)
        if not reg(w):
            continue
        controllate += 1
        if any(all(reg(w[:i] + w[i:j] * k + w[j:]) for k in range(7))
               for j in range(1, 5) for i in range(j)):
            riuscite += 1
print(f'  words of L with 4 <= |w| <= 10: {controllate}; with a pumpable decomposition (i=0..6): {riuscite}')

print('Part 3: Myhill-Nerode classes, estimated with bounded suffixes')
def tutte(n):
    return [''.join(t) for k in range(n + 1) for t in product('ab', repeat=k)]
def firme(prefissi, suffissi, appartiene):
    return {frozenset(z for z in suffissi if appartiene(x + z)) for x in prefissi}
N = 8
print(f'  a^n b^n, prefixes a^0..a^{N}, suffixes up to {2 * N}: {len(firme(["a" * k for k in range(N + 1)], tutte(2 * N), in_L))} distinct classes')
print(f'  (a|b)*abb, prefixes and suffixes up to 6: {len(firme(tutte(6), tutte(6), reg))} distinct classes')

print('Part 4: a non-regular language that satisfies the lemma with p = 3')
def in_M(w):      # a^i b^j c^k with the condition: if i = 1 then j = k
    if re.fullmatch('a*b*c*', w) is None:
        return False
    return w.count('a') != 1 or w.count('b') == w.count('c')
def pompabile(w, p):
    return any(all(in_M(w[:i] + w[i:j] * k + w[j:]) for k in range(7))
               for j in range(1, p + 1) for i in range(j))
parole = [''.join(t) for n in range(3, 11) for t in product('abc', repeat=n) if in_M(''.join(t))]
print(f'  words of M with 3 <= |w| <= 10: {len(parole)}; pumpable with p=3: {sum(pompabile(w, 3) for w in parole)}')
print(f'  Myhill-Nerode classes on the prefixes a b^j (j=0..8): {len(firme(["a" + "b" * j for j in range(9)], ["b" * i + "c" * j for i in range(10) for j in range(10)], in_M))}')

# Output:
# Part 1: a^p b^p, every decomposition xyz with |xy| <= p, |y| >= 1
#   p=1: decompositions= 1  that stay in L for i=0..3: 0
#   p=2: decompositions= 3  that stay in L for i=0..3: 0
#   p=3: decompositions= 6  that stay in L for i=0..3: 0
#   p=4: decompositions=10  that stay in L for i=0..3: 0
#   p=5: decompositions=15  that stay in L for i=0..3: 0
#   p=6: decompositions=21  that stay in L for i=0..3: 0
#   p=7: decompositions=28  that stay in L for i=0..3: 0
#   p=8: decompositions=36  that stay in L for i=0..3: 0
# Part 2: (a|b)*abb, which has a DFA with 4 states, so p = 4
#   words of L with 4 <= |w| <= 10: 254; with a pumpable decomposition (i=0..6): 254
# Part 3: Myhill-Nerode classes, estimated with bounded suffixes
#   a^n b^n, prefixes a^0..a^8, suffixes up to 16: 9 distinct classes
#   (a|b)*abb, prefixes and suffixes up to 6: 4 distinct classes
# Part 4: a non-regular language that satisfies the lemma with p = 3
#   words of M with 3 <= |w| <= 10: 228; pumpable with p=3: 228
#   Myhill-Nerode classes on the prefixes a b^j (j=0..8): 9

Part 1: for each p from 1 to 8 the admissible decompositions are p(p+1)/2 (1, 3, 6, 10, …, 36) and none survives pumping with i from 0 to 3. This confirms the argument only for those eight values of p: the proof, which holds for every p, is the one in words above. Part 2: all 254 words of (a|b)*abb with length between 4 and 10 have a pumpable decomposition with p = 4, as the lemma predicts for a regular language.

Part 3 introduces the exact characterization. Two prefixes x and y are equivalent for L if for every suffix z we have xz ∈ L ⟺ yz ∈ L; the Myhill-Nerode theorem says that L is regular if and only if the classes are finitely many, and that this number is exactly the number of states of the minimal DFA. The program estimates it with bounded suffixes: for (a|b)*abb it finds 4 classes, exactly the states of the DFA from before, while for anbn the prefixes a0…a8 give 9 distinct classes, one per prefix, and by adding prefixes new ones keep appearing. The count with bounded suffixes is an underestimate of the real number of classes, but here it is enough: there are already 9 and they keep growing.

Part 4 dispels an illusion. The language M of the strings aibjck in which "if i = 1 then j = k" satisfies the conditions of the lemma with p = 3: all 228 words of M from 3 to 10 long have a pumpable decomposition, and yet M is not regular, as shown by the 9 Myhill-Nerode classes of the prefixes abj (told apart by the suffix cj). The reason is that the lemma is a necessary condition, not a sufficient one: the fact that a language satisfies it does not prove that it is regular. That is why, when the lemma is not enough, you move on to Myhill-Nerode.

Where regular expressions stop being enough

A language like anbn requires remembering an unbounded number, and a finite automaton does not have this memory. This is why balanced parentheses, nested HTML tags and arithmetic expressions with parentheses cannot be recognized with a regular expression in the theoretical sense. Context-free grammars, the subject of article 03, add exactly that memory in the form of recursion.

Real engines are another matter compared with the theory. Backreferences (\1) let you write (cat|dog)\1, which accepts catcat and dogdog but not catdog: according to Russ Cox, who writes about it in "Regular Expression Matching Can Be Simple And Fast" (January 2007, read in full in the web version), strictly speaking expressions with backreferences are no longer regular expressions, and the best known implementations require an exponential search in the worst case. What this means for running time I measure in article 02, where I compare backtracking with the simulation of the automaton.

Here is what you can do now. You can say precisely which language an expression denotes and check it with a program, instead of trying it by hand on four examples; you can find the shortest witness when two expressions disagree; you can turn a DFA into an expression and compare the result with the automaton; you can build intersection, union, difference and complement with the product automaton; and you can prove that anbn is not regular and recognize when the pumping lemma alone is not enough.

Frequently asked questions

What is the difference between a regular expression and the regex of a programming language?

The theoretical regular expression uses only symbols, alternation, concatenation and star, and denotes a regular language. The regexes of programming languages add extensions, such as backreferences, that leave the regular languages and, according to Russ Cox, require exponential searches in the worst case; other extensions, such as character classes, are just abbreviations.

Can the pumping lemma prove that a language is regular?

No: it is a necessary condition, not a sufficient one. The language M of the fourth part of pumping.py satisfies it with p = 3 and is not regular. To prove regularity you build an automaton or an expression; to prove non-regularity, if the lemma is not enough, you use the Myhill-Nerode classes.

Why does the complement need a DFA and not an NFA?

An NFA accepts a string if at least one accepting path exists, so swapping the final states would also accept strings that have both accepting and non-accepting paths. A total DFA has a single path per string, and there the swap works. If you start from an NFA you must determinize it first.

The same series also includes article 04, top-down parsers, article 05, bottom-up parsers and article 06, semantic analysis and optimization.

Sources

Continue with article 02: deterministic and nondeterministic automata, Thompson's construction and determinization. The complete path is on the series page.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects