Lesson 67 - Lookahead & Lookbehind Assertions in Regular Expressions
Lookahead and lookbehind assertions in regular expressions allow you to match a pattern based on what comes before or after it, without including those parts in the match. They are useful for complex pattern matching.
Lookahead Assertions
A lookahead assertion checks if a certain pattern appears after the current position without consuming it.
Positive Lookahead (?=...)
It matches a group only if it is followed by a certain pattern.
Example:
let text = "apple123 banana456 cherry789";
let regex = /\d+(?= banana)/g;
console.log(text.match(regex)); // ["123"]
Explanation: It finds numbers before "banana".
Negative Lookahead (?!...)
It ensures a pattern is not followed by a certain string.
Example:
let text = "apple123 banana456 cherry789";
let regex = /\d+(?! banana)/g;
console.log(text.match(regex)); // ["456", "789"]
Explanation: It matches numbers not followed by "banana".
Lookbehind Assertions
A lookbehind assertion checks if a certain pattern appears before the current position without consuming it.
Positive Lookbehind (?<=...)
It matches a group only if it is preceded by a certain pattern.
Example:
let text = "apple123 banana456 cherry789";
let regex = /(?<=banana)\d+/g;
console.log(text.match(regex)); // ["456"]
Explanation: It finds numbers after "banana".
Negative Lookbehind (?<!...)
It ensures a pattern is not preceded by a certain string.
Example:
let text = "apple123 banana456 cherry789";
let regex = /(?<!banana)\d+/g;
console.log(text.match(regex)); // ["123", "789"]
Explanation: It matches numbers not preceded by "banana".
Summary
Assertion Type | Syntax | Matches |
---|---|---|
Positive Lookahead | X(?=Y) |
X if followed by Y |
Negative Lookahead | X(?!Y) |
X if NOT followed by Y |
Positive Lookbehind | (?<=X)Y |
Y if preceded by X |
Negative Lookbehind | (?<!X)Y |
Y if NOT preceded by X |
Try It Yourself
Experiment with different lookaheads and lookbehinds on regex101.com.