Handle Catastrophic Backtracking and Timeouts
masterBecause regexp2 supports features like lookarounds and backreferences, it is susceptible to catastrophic backtracking.
- Stack Limits: By default, the backtracking stack is limited to 100,000 slots. If exceeded, it returns
regexp2.ErrBacktrackingStackLimit. You can increase this viaOptionMaxBacktrackingStackSize(n)or disable it with a negative value. - Match Timeouts: You can set
Regexp.MatchTimeoutto bound the duration of a match.
Note on Performance: Timeout checking uses a background worker that updates a clock approximately every 100ms. This incurs a constant background CPU load (~0.15%) as long as any live matches have a timeout set, even if the matches finish quickly.
// Increase stack size
re := regexp2.MustCompile(pattern, regexp2.OptionMaxBacktrackingStackSize(200000))
// Disable stack limit
re := regexp2.MustCompile(pattern, regexp2.OptionMaxBacktrackingStackSize(-1))
// Check for error
if errors.Is(err, regexp2.ErrBacktrackingStackLimit) {
// handle limit exceeded
}