Search code examples
regexregex-greedy

How should a Lazy Optional quantifier behave?


I was reading about quantifiers and recognized the existence of the ?? (lazy optional) quantifier. I've been running some tests since then but the behaviour of this quantifier looks quite inconsistent.

Could any of you guys provide me with an example for this operator?

Also, I tried testing the regex /a??b+/ for the string abbb which gave me the unexpected match of abbb. I was as expecting bbb as match since the lazy quantifier would prioritize the smaller match possible.

For the regex /a+b??/ and the string aaab, the match is the expected aaa against the aaab matched by the greedy regex /a+b?/.

I appreciate in advance and hope you guys can help me understand what is happening here. :)


Solution

  • This can be better illustrated against aa with:

    (a?)(a+)
    

    https://regex101.com/r/c6tNrM/2

    Ensure that group 1 one has an a. Give the rest of the a chars to group 2

    vs

    (a??)(a+)
    

    https://regex101.com/r/c6tNrM/3

    Group 1 might contain an a unless something else matches it more greedily in group 2


    /a+b??/ translates into:

    • a+ - give me all of the sequential a chars
    • b?? - give me one b char if it exists char but I prefer you don't unless there is more regex to be processed. Also, if b is matched in the additional regex then I don't want it.

    /a+b?/ translates to:

    • a+ - give me all of the sequential a chars
    • b? - give me one b char if it exists