Regex lookahead and lookbehind assertions
We can think of the lookahead and lookbehind assertions as follows:
- Lookahead asserts what's on the right of (or after) the current position.
- Lookbehind asserts what's on the left of (or before) the current position.
Lookahead and lookbehind syntax
| Name | Syntax | Description |
|---|---|---|
| Positive lookahead | (?=foo) | Asserts that the current position is immediately followed by the string foo. |
| Negative lookahead | (?!foo) | Asserts that the current position is not immediately followed by the string foo. |
| Positive lookbehind | (?<=foo) | Asserts that the current position is immediately preceded by the string foo. |
| Negative lookbehind | (?<!foo) | Asserts that the current position is not immediately preceded by the string foo. |
Examples
Positive lookahead (?=...)
const regex = /bar(?=foo)/;
regex.test('barfoo'); // true
regex.test('barbaz'); // false
'barfoo'.match(regex); // ['bar']Negative lookahead (?!...)
const regex = /bar(?!foo)/;
regex.test('barfoo'); // false
regex.test('barbaz'); // truePositive lookbehind (?<=...)
const regex = /(?<=foo)bar/;
regex.test('foobar'); // true
regex.test('bazbar'); // false
'foobar'.match(regex); // ['bar']Negative lookbehind (?<!...)
const regex = /(?<!foo)bar/;
regex.test('foobar'); // false
regex.test('bazbar'); // true