Search code examples
javascriptregexnon-greedy

Why does the reluctant quantifier select the next atom regexp argument?


I understood that selects according normal quantify and returns the minimum value, but I don't understand why it's define the selection of next regexp atom to not be greedy. Does anyone know if there is a primitive expression that represents a reluctant quantifier(if it exists)? if I see the expression I can understand, but I searched and found only references to the joint use of ?= and ?! but I don't know if this is the case because I couldn't use it.

How to Works(I guess):

console.log("greedy regexp example(Expected  \"'blablabla' is a 'bla'\")");
console.log(("'blablabla' is a 'bla' so...").match(/'.*'/));
console.log("non-greedy regexp example(Expected \"''\" but returns \"'blablabla'\")");
console.log(("'blablabla' is a 'bla' so...").match(/'.*?'/));


Solution

  • * makes expressions greedy

    ? makes expressions lazy

    In this case, match(/'.*?'/) is read as "single quote followed by any character(.) zero or more times(*), but only before the next (?) single quote"

    Most regex cheat sheets will describe these kinds of expressions. Personally, I like https://www.rexegg.com/regex-quickstart.html (states * is greedy)

    What do 'lazy' and 'greedy' mean in the context of regular expressions? states * as greedy

    https://docs.oracle.com/javase/tutorial/essential/regex/quant.html states * as greedy.