Jaime Mendes
Jaime Mendes

Reputation: 23

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. :)

Upvotes: 2

Views: 245

Answers (2)

MonkeyZeus
MonkeyZeus

Reputation: 20737

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

Upvotes: 1

Barmar
Barmar

Reputation: 781255

Laziness only operates on the right, not the left. Searching for a pattern match operates from left to right. As soon as it finds a match for a, it will try to use it as long as the rest of the pattern matches. It doesn't matter whether a? is greedy or lazy.

Where the laziness matters is if you compare the patterns a+b? and a+b??, and have input like

aaab

The greedy version will match the whole string, the lazy version will match just aaa.

Upvotes: 2

Related Questions