Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regular expression: re.findall(r"(do|re|mi)+","mimi rere midore")

Tags:

python

regex

I couldn't understand why this regular expression,

re.findall(r"(do|re|mi)+","mimi rere midore"),

generates this result,

['mi', 're', 're'].

My expected result is ['mimi', 'rere', 'midore']...

However, when I use this regular expression,

re.findall(r"(?:do|re|mi)+","mimi rere midore"),

it generates the result as expected.

Can you tell me the different between two regular expressions? Thank you.

like image 939
Jung-Hyun Avatar asked Jun 30 '26 16:06

Jung-Hyun


1 Answers

The difference is in the capturing group. With a capturing froup, findall() returns only what was captured. Without a capturing group, the whole match is returned.

In your first example, the group only captures the two characters, repeated or not. In the second example, the whole match includes any repetitions.

The re.findall() documentation is quite clear on the difference:

Return all non-overlapping matches of pattern in string, as a list of strings. […] If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group.

If your (do|re|mi)+ pattern is part of a larger pattern and you want findall() to only return the full repeated set of characters, use a non-capturing group for the two-letter options with a capturing group around the whole:

r'Some example text: ((?:do|re|me)+)'
like image 148
Martijn Pieters Avatar answered Jul 03 '26 05:07

Martijn Pieters



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!