Utiliser regex lookahead assertions
Lookahead (?=...) et (?!...) assert quoi follows (ou doesn't follow) le actuel position sans consuming caractères. Zero-largeur assertions.
- 1
Lookahead asserts that a pattern follows the current position without consuming it. Positive lookahead (?=...) requires the pattern to match. Negative lookahead (?!...) requires it NOT to match. Lookahead is zero-width — it does not advance the position. This is useful for password validation and conditional matching.
- 2 Testeur de regex →
Test lookahead patterns. For password validation: (?=.*[A-Z])(?=.*[0-9]).{8,} requires at least one uppercase, one digit, and 8+ characters. The lookaheads check conditions at the same position, then .{8,} matches the full password.
- 3 Remplacement par regex →
Use lookahead in replacements. Replace \d(?=\d{3}) with , to add thousand separators: 1234567 → 1,234,567. The lookahead asserts three digits follow without consuming them, so the replacement applies at each correct position.
Questions fréquentes
- What is a zero-width assertion?
- A pattern that matches a position rather than consuming characters. Lookahead (?=...), word boundary \b, start ^, and end $ are zero-width. They assert a condition without advancing the match position. This allows checking multiple conditions at the same position, like password requirements.
- Can lookahead contain capturing groups?
- Yes. Groups inside lookahead are captured and can be referenced later. For example, (?=(\d+)) captures digits without consuming them, allowing overlapping matches. This is useful for finding all overlapping patterns that a normal match would skip.