Search This Blog

2024/03/23

Javascript Regular Expression :Negative Look Ahead

Negative lookahead is achieved with the (?!) syntax, which behaves like

(?=). It matches the previous item only if the expression contained in (?!)
does not immediately follow.

Code:
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' ]
Occurance At:27
Occurance At:40


Explanation:
This regex will match all USD words not followed by a number.
In this case one followed by 'currency' word & other followed vy 'rate' word.

No comments:

Post a Comment