Regex Lookarounds: Mastering Lookahead and Lookbehind Assertions

Discover regex lookarounds for advanced pattern matching. Learn how positive and negative lookaheads and lookbehinds work, including syntax and practical examples for effective pattern searching and validation.



Lookarounds in Regex

Regex lookarounds allow you to match a pattern only if it's followed or preceded by another pattern. There are four types of lookarounds:

  • Positive Lookahead
  • Negative Lookahead
  • Positive Lookbehind
  • Negative Lookbehind

Positive Lookahead

Positive lookahead matches the pattern only if it is followed by another pattern. It is denoted by the syntax x(?=y), which means to find x that is followed by y.

Syntax

/x(?=y)/g

The following example finds any word character that is followed by a whitespace character:

Example

var regex = /\w(?=\s)/g;
var str = "What is your name?";
var matches = str.match(regex);
console.log(matches); // Output: ['t', 's', 'y', 'r', 'n', 'm']

Negative Lookahead

Negative lookahead matches the pattern only if it is not followed by another pattern. It is denoted by the syntax x(?!y), which means to find x that is not followed by y.

Syntax

/x(?!y)/g

The following example finds any word that is not followed by a question mark ? character:

Example

var regex = /\b\w+\b(?!\?)/g;
var str = "What is your name?";
var matches = str.match(regex);
console.log(matches); // Output: ['What', 'is', 'your', 'name']

Positive Lookbehind

Positive lookbehind matches a pattern only if it is preceded by another pattern but does not include the preceding pattern in the matching result. It is denoted by the syntax (?<=y)x, which means to find x that is preceded by y.

Syntax

/(?<=y)x/g

The following example finds any word that is preceded by a whitespace character:

Example

var regex = /(?<=\s)\b\w+\b/g;
var str = "What is your name?";
var matches = str.match(regex);
console.log(matches); // Output: ['is', 'your', 'name']

Negative Lookbehind

Negative lookbehind matches a pattern only if it is not preceded by another pattern. It is denoted by the syntax (?, which means to find x that is not preceded by y.

Syntax

/(?

The following example finds any word that is not preceded by a whitespace character:

Example

var regex = /(?

In this example, it finds a word that is not preceded by a whitespace character. The pattern \b\w+\b finds the whole word, and \s is for the whitespace character.