X(?=Y) //For positive lookaheads X(?!Y) //For negative lookaheads
Types of lookaheads: There are two types of lookaheads as follows:
- Positive lookaheads: It will look to make sure that a particular element is there in the search pattern, but actually won’t match it. A positive lookahead is created by enclosing a certain pattern between (?= and ).
- Negative lookaheads: It will look to make sure that a particular element is not there in the search pattern. A negative lookahead is created by enclosing a certain pattern between (?! and ).
Note: The ‘?’ character may also be used as a quantifier.
Lookaheads are a bit confusing to understand, so let’s take some examples.
Example 1: This example demonstrates positive lookahead.
Explanation: In the above example, exp matches “butter” only if it is followed by “fly“.After testing the expression against word1, code outputs the contents of RegExp.$1, which is ‘butter‘ not ‘butterfly‘.The “fly” part of the pattern is contained inside of a lookahead and so isn’t returned as part of the group.
Example 2: The previous example can be converted to negative lookahead:
Explanation: Here, the pattern matches “buttermilk” but not “butterfly” as “fly” doesn’t follow “butter“. After testing against word2, RegExp.$1 contains “butter” once again, not “buttermilk”.
Let’s have a practical example to understand lookaheads properly:
Problem Statement: Write a regex to find all the items which have a present status of ‘sold’.
The regex for the above requirement will be:
/ bike(?=\s+sold) /
In this way, we can match certain words not followed by some elements. These elements can be characters, or groups
- Google Chrome
- Internet Explorer
Please Login to comment...