50 Finding Multiple Instances
50 Finding Multiple Instances
Up to this point, all we’ve seen is how to find the first match in a string. But
what if you have a string that has multiple matches in it. Let’s review how to
find a single match:
import re
silly_string = "the cat in the hat"
pattern = "the"
match = re.search(pattern, silly_string)
print (match.group())
#'the'
Now you can see that there are two instances of the word “the”, but we only
found one. There are two methods of finding both. The first one that we will
look at is the findall function:
import re
silly_string = "the cat in the hat"
pattern = "the"
print (re.findall(pattern, silly_string))
#['the', 'the']
The findall function will search through the string you pass it and add each
match to a list. Once it finishes searching your string, it will return a list of
matches. The other way to find multiple matches is to use the finditer
function.
import re
As you might have guessed, the finditer method returns an iterator of Match
instances instead of the strings that you would get from findall. So we needed
to do a little formatting of the results before we could print them out. Give this
code a try and see how it works.