Aller au contenu
uencoder

Optimiser regex pour performance

Lent regex peut cause ReDoS (Regular Expression Denial de Service). Apprendre en identifier et fix catastrophic backtracking, utiliser atomic groups, et anchor motifs.

  1. 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. 2
    Testeur de regex →

    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. 3
    Remplacement par regex →

    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.

Questions fréquentes

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 résolvant cette tâche

Outils associés