Regex Performance Optimization Tips and Tricks
optimization, performance, regex
Solution
- Use the non-capturing group `(?:pattern)` when you need to repeat a grouping but don't need to use the captured value that comes from a traditional `(capturing)` group.
- Use the atomic group (or non-backtracking subexpression) when applicable `(?>pattern)`.
- Avoid catastrophic backtracking like the plague by designing your regular expressions to terminate early for non-matches.
I created a video demonstrating these techniques. I started with the very poorly written regular expression in the catastrophic backtracking article `(x+x+)+y`. And then I made it 3 million times faster after a series of optimizations, benchmarking after every change. The video is specific to .NET but many of these things apply to most other regex flavors as well:
.NET Regex Lesson: #5: Optimization
Problem
After reading a pretty good article on regex optimization in java I was wondering what are the other good tips for creating fast and efficient regular expressions?