498

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
  • Recursive REs are a different beast. You want to repeat the search.
    – outis
    Jan 15, 2011 at 4:29

1 Answer 1

847

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']
8
  • 40
    finditer was what I was looking for. I'm surprised that one returns Match objects and the other strings. I was expecting to use a match_all or match_iter function.
    – dsclose
    Dec 7, 2015 at 13:55
  • 42
    DISCLAIMER: those will find only non-overlapping matches Sep 10, 2016 at 22:16
  • 5
    @AntoineLizée, how does one find iterations WITH overlap?
    – Raksha
    May 10, 2017 at 23:49
  • 25
    @Raksha - Use re.search in a loop. It'll return a Match object. You'll want to pass in Match.start() + 1 as the pos argument for re.search for the next iteration of the loop. May 31, 2017 at 17:31
  • 12
    If the match contains more than one group, findall will return a list of matching tuples, not a list of matching strings.
    – rodorgas
    Jun 12, 2018 at 3:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.