1. Home
  2. Theory of Computation
  3. Regular Expressions

Regular Expressions

Patterns for text — and the automata hidden inside them. Type a regex, watch Thompson's construction turn it into an NFA, and run it on your text in 3D.

Interactive 3DIntermediate12 min readTOCUpdated

Drag to rotate · Right-drag to pan · Click, then scroll to zoom · Space play · Left arrowRight arrow step

What's happening

A regular expression describes a pattern of text. Under the hood, a regex engine turns it into an automaton. Here, Thompson’s construction builds an NFA from the regex, and we run it on the text. Press Match.

Pseudocode

  1. Thompson’s construction: build an NFA piece by piece
  2. a → one arrow; AB → join; A|B → two branches; A* → loop with ε arrows
  3. simulate: current ← ε-closure({start})
  4. for each character c: current ← ε-closure(move(current, c))
  5. match if the accept state is in current at the end
Read this model as text · 9 steps

One run of the model above, written out step by step. Useful with a screen reader, on a slow connection, or for quick revision. The values may differ from the run on your screen.

  1. A regular expression describes a pattern of text. Under the hood, a regex engine turns it into an automaton. Here, Thompson’s construction builds an NFA from the regex, and we run it on the text. Press Match.
  2. Regex (a|b)*abb became an NFA with 14 states (arrows labelled ε can be taken without reading anything). Start in the ε-closure of S: {6, 4, 7, 8, 0, 2}.
  3. Read 'a': follow the 2 arrow(s) labelled a, then add everything reachable by ε → 9 active state(s).
  4. Read 'a': follow the 2 arrow(s) labelled a, then add everything reachable by ε → 9 active state(s).
  5. Read 'b': follow the 2 arrow(s) labelled b, then add everything reachable by ε → 9 active state(s).
  6. Read 'a': follow the 2 arrow(s) labelled a, then add everything reachable by ε → 9 active state(s).
  7. Read 'b': follow the 2 arrow(s) labelled b, then add everything reachable by ε → 9 active state(s).
  8. Read 'b': follow the 2 arrow(s) labelled b, then add everything reachable by ε → 8 active state(s).
  9. End of text and the accept state A is active → "aababb" matches (a|b)*abb.

Try this in the 3D model

  • Run the example (a|b)*abb on aababb, then change the text to aabab. Why does it fail?
  • Try colou?r on both "color" and "colour".
  • Look at the ε arrows created by a * — which one makes the loop?
  • Write your own regex, e.g. (ab)+ and test it on "ababab".

What is a regular expression?

A regular expression (regex) is a compact way to describe a set of strings — a pattern. You use them in search boxes, form validation, programming and the command line.

The three core operations

Every regex is built from single characters using just three operations:

Operation Syntax Meaning Example
Concatenation AB A followed by B ab matches “ab”
Union (or) A|B A or B a|b matches “a” or “b”
Kleene star A* zero or more A’s a* matches “”, “a”, “aa”, …

Handy shorthands built from these:

Shorthand Means
A+ one or more = AA*
A? optional = A|ε
. any single character
[a-z] any character in the range (not used in our demo)

Parentheses group: (ab)* matches “”, “ab”, “abab”, …

From regex to automaton: Thompson’s construction

Kleene’s theorem says regular expressions and finite automata describe exactly the same languages. (For the other direction, from automaton to regex, see DFA to Regular Expression.) Thompson’s construction turns any regex into an NFA with ε-moves, recursively:

  • a single character a → two states joined by an arrow labelled a,
  • AB → connect A’s end to B’s start with ε,
  • A|B → a new start with ε-arrows to both, and both ends ε-arrow to a new end,
  • A* → ε-arrows that let you skip A or loop back to repeat it.

The 3D model builds exactly this NFA from your regex. S is the start state and A the accept state.

Running it: sets of states

  1. Start with the ε-closure of S — all states reachable with ε-arrows alone.
  2. For each character, follow every arrow labelled with it, then take the ε-closure again.
  3. At the end, the string matches if the accept state is among the active states.

This takes O(n · m) time — linear in the text. Tools like grep, RE2 and Rust’s regex crate use this approach.

Code

import re

print(bool(re.fullmatch(r"(a|b)*abb", "aababb")))   # True
print(bool(re.fullmatch(r"colou?r", "colour")))     # True

# Practical patterns
email = re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+")
print(email.findall("write to [email protected] or [email protected]"))

phone = re.compile(r"\+?91[\s-]?\d{5}[\s-]?\d{5}")   # Indian mobile numbers
print(bool(phone.fullmatch("+91 98765 43210")))

re.fullmatch checks the whole string (like the model); re.search finds the pattern anywhere inside it.

Backtracking and “catastrophic” regexes

Python, Java and JavaScript use backtracking engines, which support extra features (back-references like (\w)\1) but can take exponential time on patterns such as (a+)+b against “aaaaaaaaaaaaaaaaaaaaaa!”. Such bugs have taken real websites down. Keep patterns simple, or use a linear-time engine.

Where are regular expressions used?

Search and replace in editors, input validation (emails, phone numbers, PIN codes), log analysis, compilers’ lexical analysers, data cleaning, and grep/sed on the command line.

Common mistakes

  • Forgetting that . matches any character — escape it as \. for a literal dot.
  • Using regex for nested structures like HTML or balanced brackets — that needs more than a finite automaton.
  • Confusing “match anywhere” with “match the whole string”.

Complexity at a glance

Case / operationTimeWhy
Thompson NFA size (regex length m)O(m) states
Matching a text of length nO(n · m)Set-of-states simulation — no exponential blow-up.
Backtracking engines (worst case)exponentialCatastrophic backtracking on patterns like (a+)+b.
Extra spaceO(m)

Quick check

Test yourself — pick an answer to see if you got it.

1. Which strings does the regex ab*c match?

2. What does the ? operator mean in colou?r?

3. What is an ε (epsilon) transition in an NFA?

4. Regular expressions describe exactly the languages recognised by…

Saved in this browser.
Spotted a mistake or a bug in the 3D model?

Report a mistake

in Regular Expressions. Thank you — every report makes the lesson better for the next reader.

We'll also include a link to the step of the 3D model you're on and your browser type, so we can reproduce it.