Zum Inhalt springen
uencoder

Regex Performance Leitfaden

Referenz für regex performance optimization und ReDoS (Regular Expression Denial von Dienst) prevention.

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

Verwandte Tools

参考链接