How One Innocent Regex Can Freeze a Single-Threaded Server
Regular expressions look compact, which makes them deceptively easy to ship without stress-testing malformed inputs. Consider an email-like validation pattern written with nested quantifiers:
/^([a-zA-Z0-9_.-]+)+@([a-zA-Z0-9.-]+)+$/
On valid emails, it finishes in microseconds. Pass a 35-character string of letters ending in an exclamation mark (with no @ sign), and the NFA regex engine enters Catastrophic Backtracking (ReDoS)—exploring millions of ways to partition the same characters between the inner + and outer + before finally failing. On Node.js or browser main threads, that single string pins CPU utilization at 100%. Flattening the pattern to /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9.-]+$/ restores linear O(n) execution immediately.
Core Rules for Safe, Predictable Regular Expressions
JavaScript's RegExp engine uses a backtracking Non-Deterministic Finite Automaton (NFA). Follow three discipline rules so execution time scales linearly with input length:
- Never Nest Repeating Quantifiers: Avoid
(x+)+,([a-z]*)*, or overlapping alternations like(a|ab)+. - Anchor Validation Patterns Explicitly: Wrap full-string validators in
^and$(and enforce a sensible maximum string length before running regex). - Prefer Negated or Specific Character Classes: Use
[^"\r\n]*instead of unbounded.*?when matching delimited tokens.
Test & Debug Regular Expressions Live
Real-time match highlighting, capture group inspection, flag toggles, and battle-tested reference patterns.
Four Battle-Tested Linear-Time Patterns
- Indian Mobile Number (10 Digits):
^[6-9]\d{9}$ - CSS Hex Color Code:
^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$ - ISO 8601 Calendar Date (YYYY-MM-DD):
^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$ - URL Slug:
^[a-z0-9]+(?:-[a-z0-9]+)*$
