Utiliser regex quantifiers: *, +, ?, {n,m}
Quantifiers specify comment plusieurs times un motif repeats. Apprendre greedy, lazy, et possessive matching en avoid catastrophic backtracking.
- 1
Quantifiers: * (0 or more), + (1 or more), ? (0 or 1), {n} (exactly n), {n,m} (n to m), {n,} (n or more). By default they are greedy (match as much as possible). Add ? for lazy (match as little as possible): *?, +?, ??. Add + for possessive (no backtracking): *+, ++. Lazy is common; possessive prevents catastrophic backtracking.
- 2 Testeur de regex →
Test greedy vs lazy quantifiers. Compare .* (greedy, matches to end) vs .*? (lazy, matches minimum). For HTML like <div>content</div>, <.*> matches the entire string (greedy), while <.*?> matches <div> only (lazy).
- 3 Remplacement par regex →
Use quantifiers in replacements. Replace \d{4} with **** to mask 4-digit numbers, or [a-z]+ to replace words. Test with various inputs to verify the quantifier matches the intended number of repetitions.
Questions fréquentes
- What is catastrophic backtracking?
- When a regex with nested quantifiers (e.g., (a+)+) fails to match, the engine tries exponentially many combinations before giving up. This can hang for minutes on short input. Fix with possessive quantifiers (a++)+, atomic groups, or rewrite the pattern. Always set a timeout for regex on untrusted input.
- When to use lazy vs greedy?
- Use lazy (*?, +?) when you want the shortest match, typically when matching between delimiters (HTML tags, quoted strings). Use greedy (*, +) when you want the longest match, typically when matching to end of line or when the pattern is anchored. Most real-world cases use lazy for delimited content.