Optimize regex for performance
Slow regex can cause ReDoS (Regular Expression Denial of Service). Learn to identify and fix catastrophic backtracking, use atomic groups, and anchor patterns.
- 1
Common performance issues: (1) Catastrophic backtracking — nested quantifiers like (a+)+ cause exponential backtracking. (2) Unanchored patterns — .* scans the entire string. (3) Overly broad alternation — (a|ab|abc) tries all branches. Fixes: use possessive quantifiers (a++), atomic groups (?>...), specific character classes instead of ., and anchor patterns with ^ and $.
- 2 Regex Tester →
Test the optimized pattern against various inputs, including worst-case inputs that previously caused slowness. Compare execution time. A pattern that took 10 seconds should complete in milliseconds after optimization.
- 3 Regex Replace →
Test the optimized pattern in replacement operations. Replacements may be slower than matching because they process all matches. Use global flag (g) for multiple replacements and verify the output matches the original pattern's behavior.
Frequently asked questions
- What is ReDoS?
- Regular Expression Denial of Service — a malicious input that causes a regex to take exponential time, hanging the server. Example: (a+)+ against "aaaaaaaaaaaaaaaaaaaab" tries 2^n combinations. Fix with possessive quantifiers (a++)+, atomic groups, or rewrite the pattern. Set a timeout on regex operations.
- How do I prevent ReDoS?
- Use safe regex patterns (no nested quantifiers, use possessive/atomic groups), set timeouts on regex operations, use linear-time regex engines (RE2, Rust regex) for untrusted input, and test patterns against worst-case inputs. Libraries like safe-regex2 can verify patterns are safe.
Workflows that solve this
Learn more
Want to understand why?