Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find all matches to a regular expression in Python?

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?

like image 780
kjakeb Avatar asked Jan 15 '11 03:01

kjakeb


People also ask

How do I find all matches in regex?

The method str. match(regexp) finds matches for regexp in the string str . If the regexp has flag g , then it returns an array of all matches as strings, without capturing groups and other details. If there are no matches, no matter if there's flag g or not, null is returned.

What method regex returns a list of strings containing all matches?

The re. findall() function returns a list of strings containing all matches of the specified pattern.

How do you use Find all in Python?

findall() is probably the single most powerful function in the re module. Above we used re.search() to find the first match for a pattern. findall() finds *all* the matches and returns them as a list of strings, with each string representing one match.


1 Answers

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.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats') # Output: ['cats', 'dogs']  [x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')] # Output: ['all cats are', 'all dogs are'] 
like image 179
Amber Avatar answered Oct 12 '22 08:10

Amber