跳到主要内容
uencoder

Regex Performance Guide

Reference 为 regex 性能优化和 ReDoS (Regular Expression Denial 的 Service) 预防.

ReDoS Vulnerabilities

Catastrophic backtracking occurs when ambiguous patterns cause exponential backtracking on non-matching input. Nested quantifiers like (a+)+ or (a*)* are classic ReDoS patterns. Overlapping alternation (a|a) causes unnecessary backtracking. The evil regex (a+)+$ takes exponential time on aaaa...!. ReDoS is a denial-of-service vector in server-side input validation. Tools like safe-regex and static analysis detect vulnerable patterns. RE2 is immune to ReDoS by design.

nested quant
(a+)+, (a*)*
exponential
overlapping
a|a
redundant
detection
safe-regex
static analysis

Optimization Techniques

Use specific character classes instead of broad . where possible. Anchor patterns (^, $) to reduce search space. Use possessive quantifiers or atomic groups to prevent unnecessary backtracking. Prefer non-capturing groups (?:...) when capture is not needed. Order alternation by likelihood (most common first). Use lazy quantifiers (*?) only when needed; greedy is often faster. Compile regex once and reuse. For untrusted input, use RE2 or set a timeout. Profile with regex debuggers to identify backtracking hotspots.

specific classes
[a-z] not .
narrower
possessive
Prevent backtracking
++, *+
compile once
Reuse pattern
avoid recompilation

相关工具

参考链接