Groups with RE | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Groups with RE

import re testo="aaabbbabababaabbaabbaabbaaaabbbb" pattern=r"(a|b)+" print(re.findall(pattern,testo)) I don't understand why this code gives me a different result from the case where I set pattern="[ab]+". Thanks for your time :)

5th Mar 2020, 1:59 AM
William Bertolasi
William Bertolasi - avatar
1 Answer
+ 1
Thats the behaviour of greedy quantifier with capturing group. It'll only take the last match from group. So the string aaabbbabababaabbaabbaabbaaaabbbb will only take the last b. You can however enclose it again in another group ((a|b)+). But using character class [ab]+ is much better here
5th Mar 2020, 11:32 AM
Taste
Taste - avatar