Stage 1 — Regex → NFA (Thompson's construction)
Build a non-deterministic machine directly from the shape of the expression.
What this stage is doing
Thompson's construction turns any regular expression into a machine, mechanically. It never has to be clever, because it never looks at the expression as a whole.
For a*b it first builds a two-state machine for the single character 'a'. Then the star wraps that in a loop, adding a bypass edge so zero repetitions is allowed. Then it builds another two-state machine for 'b'. Finally concatenation joins the two pieces end to end with an empty (ε) edge. Four steps, four small machines, one result.
The ε edges are transitions that consume no input — they exist purely to glue fragments together, which is what makes the construction so mechanical.
- 1.Type a regular expression, e.g. a*b (zero or more a's, then a b)
- 2.Press Run
- 3.Watch the NFA assemble one construct at a time, then the DFA appear below it
letters, digits and ( ) | * + ? — up to 64 characters
What the code is doing under the hood
Thompson's construction is NOT one large function with a switch over regex syntax. It is a set of tiny builders — one per construct: match a single character, handle star, handle concatenation, handle alternation — each about ten lines long.
Every builder returns a fragment with exactly ONE entry state and ONE exit state. Because every fragment has that same shape, fragments plug into each other, and the whole machine is assembled by walking the expression's syntax tree bottom-up. The recursion does the work; no builder knows about any other.
Run this demo to see the code that executed.