Skip to content
the poor coder

regex look behind

Poor Man
Published
Reading time
1 min read
On this page

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":

JavaScript

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":

JavaScript

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC