Usar regex lookbehind assertions
Lookbehind (?<=...) y (?<!...) assert qué precedes el actual position. Supported en moderno engines (ES2018+, Java, .NET, PCRE).
- 1
Lookbehind asserts that a pattern precedes the current position. Positive (?<=...) requires it, negative (?<!...) forbids it. Lookbehind is zero-width. Unlike lookahead, lookbehind must be fixed-length in some flavors (Java, PCRE before 10.0), but variable-length is supported in .NET, JavaScript (ES2018+), and PCRE 10.0+.
- 2 Probador de regex →
Test lookbehind patterns. Replace (?<=\$)\d+ to match numbers after a dollar sign: "$100" matches "100". Use (?<!\d)\d+(?!\d) to match standalone numbers (not adjacent to other digits). Lookbehind checks what precedes without consuming it.
- 3 Reemplazo con regex →
Use lookbehind in replacements. Replace (?<=\b\w)\w with * to mask all but the first letter of each word: "hello world" → "h**** w****". The lookbehind asserts a word character precedes, so the first letter is not replaced.
Preguntas frecuentes
- Is lookbehind supported in all browsers?
- Lookbehind is supported in ES2018+ (Chrome 62+, Firefox 78+, Safari 16.4+). It is not supported in older Safari and some regex flavors. For maximum compatibility, restructure the pattern to use lookahead instead, or use a polyfill/preprocessing approach.
- What is variable-length lookbehind?
- Lookbehind where the pattern can match varying lengths: (?<=ab|abc)d matches d preceded by "ab" or "abc". This is supported in .NET, JavaScript (ES2018+), and PCRE 10.0+, but not in Java or older PCRE. For fixed-length-only flavors, use alternation with same-length branches or restructure.