How can I find all matches to a regular expression

2018-12-31 21:37发布

问题:

In a program I\'m writing I have Python use the re.search() function to find matches in a block of text and print the results. However, the program exits once it finds the first match in the block of text.

How do I do this repeatedly where the program doesn\'t stop until ALL matches have been found? Is there a separate function to do this?

回答1:

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.