regex look behind

What is Regex Look Behind?

Regex Look Behind is a useful feature in regular expressions that matches a pattern only if it is preceded by another pattern. In other words, it allows you to specify a pattern that must occur immediately before the main pattern for a match to be found.

Positive Look Behind

A positive look behind is denoted by the (?<=pattern) syntax. It matches the main pattern only if the preceding pattern is found. Let's take an example of finding all the words that come after the word "hello":


const str = 'hello world, hello everyone, hello';
const regex = /(?<=hello )\w+/g;
const matches = str.match(regex);

console.log(matches);
// Output: ["world", "everyone"]
    

In this example, we use the positive look behind to match any word character that comes immediately after the word "hello". The (?<=hello ) pattern matches the word "hello" followed by a space, but it is not included in the final match.

Negative Look Behind

A negative look behind is denoted by the (?<!pattern) syntax. It matches the main pattern only if the preceding pattern is not found. Let's take an example of finding all the words that do not come after the word "hello":


const str = 'hello world, hi everyone, howdy';
const regex = /(?<!hello )\w+/g;
const matches = str.match(regex);

console.log(matches);
// Output: ["hi", "howdy"]
    

In this example, we use the negative look behind to match any word character that does not come immediately after the word "hello". The (?<!hello ) pattern matches any position that is not preceded by the word "hello" followed by a space.

Regex Look Behind is a powerful feature in regular expressions that allows you to match patterns with more precision. It can be used in combination with other regex features such as positive and negative look ahead to create complex patterns that match specific text patterns.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe