5 Common Regex Mistakes Every Developer Makes
Regex is a developer superpower. It can replace 50 lines of complex string parsing logic with 1 line of code. But "With great power comes great responsibility." A bad regex can crash your server, create security vulnerabilities, or silently corrupt your data.
Here are the 5 most common mistakes we see developers make (and how to fix them).
1. Catastrophic Backtracking (The Server Killer)
Have you ever written a regex that works on small strings but hangs your CPU at 100% on long ones? This is usually due to nested quantifiers.
The Culprit: (a+)+
If you feed this string aaaaaaaaaaaaaaaaaaaaX, the engine tries exponentially many ways to split the as between the inner and outer loop.
The Fix: Avoid nested quantifiers. Be specific.
Better: a+
2. Using .* (The Greedy Match)
* (star) is "greedy". It eats as much as it can.
Example: Extracting HTML tags.
Text: <div>first</div><div>second</div>
Regex: <div>.*</div>
Match: <div>first</div><div>second</div> (The WHOLE string!)
It matched from the first opening div to the last closing div.
The Fix: Use "Lazy" matching .*? or a negated character class.
Better: <div>.*?</div> or <div>[^<]*</div>
3. Forgetting to Escape Special Characters
You want to match a price: Only $5.00!
Regex: Only $5.00!
Result: Matches "Only 5000!" or "Only $5a00!".
Why? Because . means "any character" and $ means "end of line" (context dependent).
The Fix: Escape them!
Correct: Only \$5\.00!
4. Assuming \s is just space
You want to split words by space.
Regex: (literal space)
Result: Fails on tabs, newlines, and non-breaking spaces.
The Fix: Use \s. It matches spaces, tabs \t, newlines \n, and carriage returns \r.
5. Not Using Anchors (^ and $)
You want to validate a username: "admin".
Regex: admin
Result: Matches "superadmin", "administrator", "badadmin".
Without anchors, regex searches anywhere in the string.
The Fix: Anchor it to the start and end.
Correct: ^admin$
Conclusion
Regex is tricky. "It looks right" is not enough. You need to test it against edge cases. Before you deploy a regex to production, paste it into our Online Regex Tester. We visualize the matches so you can see exactly what is being captured (and avoiding those greedy bugs!).
Found this helpful?
Join thousands of developers using our tools to write better code, faster.