Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
779 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)+)'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...