Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
776 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...