Saltar al contenido
uencoder

Optimizar regex para performance

Lento regex puede cause ReDoS (Regular Expression Denial de Servicio). Aprender a identificar y fix catastrophic backtracking, usar atomic groups, y anchor patrones.

  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
    Probador 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
    Reemplazo con 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.

Preguntas frecuentes

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.

Flujos que resuelven esta tarea

Herramientas relacionadas