5 Regex Mistakes That Pass Your Tests and Break Production
Regex bugs are rarely syntax errors. They're logic errors that pass your three happy-path test strings and then melt production. Here are the five I see most. 1. Greedy quantifiers eating too much <b>.*</b
Regex bugs are rarely syntax errors. They're logic errors that pass your three happy-path test strings and then melt production. Here are the five I see most.
1. Greedy quantifiers eating too much
<b>.*</b>
On <b>a</b> and <b>b</b> this matches the whole string. Use the lazy form <b>.*?</b> or, better, a negated class: <b>[^<]*</b>.
2. Forgetting to anchor
\d{3} "validates" abc12345xyz. For validation use ^\d{3}$. Without anchors you are searching, not validating.
3. Unescaped dots
example.com also matches exampleXcom. Escape it: example\.com.
4. Catastrophic backtracking
(a+)+$ on a long string of as followed by ! can freeze a thread for minutes. Nested quantifiers over overlapping patterns are the smell. Prefer unambiguous patterns, and cap input length.
5. Not testing with the real flags
^ and $ change meaning with the m flag, . ignores newlines without s, and \w ignores accents without u-aware classes. Always test with the exact flags your code uses.
How I debug these
I paste the pattern and a nasty sample into a live tester with match highlighting and capture groups, then read an explanation of each token. I built a free one that runs entirely in your browser (nothing is uploaded), plus a token-by-token explainer:
Disclosure: I'm the author of Web Developer Toolbox. What's the worst regex bug you've shipped?
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.