DEV Community

zhihu wu
zhihu wu

Posted on

3 Regex Patterns That Save Hours of Debugging

Every developer has been there: staring at a regex that should work but doesn't. Here are three patterns I debugged this month that turned hours of head-scratching into one-line fixes.

1. Non-Greedy Matching (.*?)

The classic mistake: matching everything between two delimiters.

# Wrong — grabs everything from first <div> to the LAST </div>
<div>.*</div>

# Right — stops at the first </div>
<div>.*?</div>
Enter fullscreen mode Exit fullscreen mode

The ? after * makes the quantifier "lazy" — it matches as little as possible instead of as much as possible. This single character fixes more regex bugs than anything else.

2. Lookaheads Without Lookbehinds

Need to match something only when followed by something else? That's a lookahead. Need the opposite? Lookbehinds aren't supported everywhere.

# Match "USD" only when followed by a number
USD(?=\d+)

# Match a number only when preceded by "$"
(?<=\$)\d+\.?\d*
Enter fullscreen mode Exit fullscreen mode

Lookaheads work in every browser and language. Lookbehinds fail silently in Safari. When in doubt, capture instead.

3. Capture Groups vs. Non-Capturing

Every (...) creates a capture group. If you're grouping for precedence (not extraction), use (?:...).

# Creates 2 unnecessary capture groups
(https?|ftp)://(www\.)?(example\.com)

# Cleaner — only captures what matters
(?:https?|ftp)://(?:www\.)?(example\.com)
Enter fullscreen mode Exit fullscreen mode

When you're writing a replacement with $5 and $7, you'll thank yourself for keeping the group count low.


Quick test tip: When debugging regex, I use a free online regex tester that shows match highlighting and capture groups in real time. Paste your pattern, write test cases, iterate — all in the browser.

What's the worst regex bug you've shipped? Drop it in the comments — I'll go first: I once used [0-9] instead of [0-9]+ in a credit card validator…

Top comments (0)