Skip to content
Compiling Quantifiers to NFA
step 1/5

Reading — step 1 of 5

Read

~1 min readNFA Construction & Simulation

Compiling Quantifiers to NFA

Quantifier sub-NFA constructions:

a? — zero or one. Add an ε bypass:

   ε
   ↓
(start) --ε--> (a) --ε--> (end)
        --ε----------------↑

a* — zero or more. Bypass + loop:

   ε
   ↓
(start) --ε--> (a) --ε--> (end)
                   ↑__ε____|
        --ε----------------↑

a+ — one or more. Required first match + loop:

(start) --ε--> (a) --ε--> (end)
                   ↑__ε____|

The trick: every quantifier wrapper has ONE entry and ONE exit, so they nest cleanly. (ab)*c = wrap the ab NFA in a * shell, then concat with c.

For {n,m}: unroll N copies + (M-N) optional copies. a{2,4} becomes aaa?a? essentially. For unbounded {n,}: N concatenated, then a * of the same.

Catastrophic backtracking REGEXes that explode in PCRE:

  • (a+)+b — exponential in backtracking engines, linear in NFA
  • (a|aa)*c — same
  • (a*)* — same

NFA simulation handles all of these in O(text * states), no exceptions.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…