Search This Blog

2024/03/27

Javascript Regular Expression : Positive Look Ahead

 


JavaScript allows you to specify that a portion of a regular expression matches
only if it is or is not followed by a particular subexpression. The (?=) syntax
specifies a positive lookahead; it only matches the previous item if the item
is followed immediately by the expression contained in (?=). The lookahead
expression is not included in the match.


lets suppose you want to match all those USD characters which are
followed by some digits. Simply you want to match all those USD
characters which are immediately followed by numbers for example
you want to match

Code:
//positive look ahead
var line ="USD 100 USD 350 USD 345.56 USD currency USD rate"
var pattern=/USD(?=\s\d+\.{0,}\d+)/gm

var result = line.match(pattern)
console.log(result)

var lastIndex
while ((match = pattern.exec(line))) {
lastIndex = match.index;
console.log("Occurance At:" + lastIndex)
}

Output:
[ 'USD', 'USD', 'USD' ]
Occurance At:0
Occurance At:8
Occurance At:16

Explanation:
Here first the engine will search for U after finding U upper case the
engine will look for S if it finds it will see if it is immediately
followed by D.

In case of a USD match the engine will enter lookahead and finds that it
is a positive lookahead and in this look ahead there is a space followed
by an optional number one or more quantifier then an optional dot and
after dot there is one or more digits.

This regex will match all USD words followed by a number of one or more
digits.

No comments:

Post a Comment