πŸ”RegexLab
πŸ§°πŸ“
2026-07-08Β·5 min read

Regex Performance: 5 Tips to Avoid Slow Patterns

Optimize your regex patterns to prevent catastrophic backtracking and slow matches.

Regex Performance

Bad regex can cause catastrophic backtracking, freezing your application. Here's how to avoid it.

1. Be Specific

Bad: .* (matches everything)
Good: [^\n]* (matches everything on one line)

2. Avoid Nested Quantifiers

Bad: (a+)+ can cause exponential backtracking
Good: a+ (same result, no backtracking)

3. Use Non-Capturing Groups

Use (?:pattern) instead of (pattern) when you don't need the captured value. It's faster.

4. Anchor Your Patterns

Add ^ and $ to avoid scanning the entire string unnecessarily.

5. Use Possessive Quantifiers

a++ (possessive) prevents backtracking. Not supported in all engines but great when available.

Catastrophic Backtracking Example

^(a+)+$ with input "aaaaaaaaaaaaaaaaaaab" can take minutes to fail.

Fix: ^a+$ β€” same logic, no exponential backtracking.