Search This Blog

2024/03/23

Javascript Regular Expression: Greedy Matching

One particularly challenging aspect facing those new to regular expressions is

greedy matching. Often termed aggressive or maximal matching.A simple way to
think about this is that JavaScript will continue matching characters if at
all possible.

Here is example

Code:
var pattern =/(ma.*ing)/
var sentence = "Regular Expression matching can be daunting task"
pattern.test(sentence)
console.log(RegExp.$1)

Output:
matching can be daunting

Explanation:

you might think that the pattern would match the wordmatching”.
but the actual output is shown in the following illustration.
JavaScript matchesthe longest substring it can, in this case
from the initialmain matching all the way to the final
ingindaunting.”

No comments:

Post a Comment