Regular expressions are everywhere — they filter emails, validate passwords, search source code and power every text editor you have ever used. The basic idea is simple: describe a pattern, hand it to an engine, get back all the matching strings.
For the pure kind — the regexes that use only concatenation, alternation |, and the Kleene star * — matching is fast. A textbook algorithm converts any such pattern to a non-deterministic finite automaton (NFA), simulates all paths in parallel, and answers in time , where n is the text length and m is the pattern length. No exponential blowup, ever.
But modern regex engines add one extra feature that changes everything: backreferences. A backreference like \1 says "match whatever the first capture group just matched." That tiny addition — the ability to refer back to what was already captured — lifts the matching problem out of the polynomial world entirely. Matching a regex with backreferences against a string is NP-complete (proven by Aho, 1980).
Even without backreferences, PCRE-style engines that use recursive backtracking instead of NFA simulation can be catastrophically slow on carefully crafted inputs. A 30-character string can stall a server for seconds; a 60-character string for hours. That failure mode is called ReDoS — Regular Expression Denial of Service — and it has taken down production systems at Cloudflare, Stack Overflow and many others.
Comments
Loading comments...