Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between (ab)+? and (ab)+ when I use it in boost:regex? [duplicate]

Tags:

regex

perl

+? Matches the previous atom one or more times, while consuming as little input as possible.

I don't understand this,can someone help me?

like image 462
Robin Avatar asked Nov 21 '25 21:11

Robin


1 Answers

(ab)+? will try to match ab which occurs at least once and it will return as soon as it finds the pattern, hence it's lazy.

(ab)+ will try to match all occurrences of ab which occur at least once and then it will return, hence it's greedy.

Demo: https://regex101.com/r/rC2oB9/1 and https://regex101.com/r/hP7lM9/1

Notice that in first demo first occurrence of ab was matched (which is highlighted) whereas in second demo all occurrences of ab were matched (highlighted)

Note: A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data.

See: What do lazy and greedy mean in the context of regular expressions?

like image 199
Chankey Pathak Avatar answered Nov 23 '25 12:11

Chankey Pathak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!