Search This Blog

2024/03/23

Javascript Regular Expression:Non Greedy Matching

You can force a quantifier (*, +, ?, {m}, {m,}, or {m,n}) to be

nongreedy by following it with a question mark. Doing so forces the expression
to match the minimum number of characters rather than the maximum.

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

Output:
matching


Explanation:
The output shows that the interpreter found the first shortest matching pattern in
the string

No comments:

Post a Comment