0% found this document useful (0 votes)
34 views2 pages

50 Finding Multiple Instances

This document discusses finding multiple instances of a pattern in a string using regular expressions in Python. It explains that the findall function searches a string and returns a list of all matches. The finditer function returns an iterator that allows iterating over each Match object found and accessing the start and end indexes of each match. Both methods allow finding all matches of a pattern in a string, unlike re.search which only returns the first match.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views2 pages

50 Finding Multiple Instances

This document discusses finding multiple instances of a pattern in a string using regular expressions in Python. It explains that the findall function searches a string and returns a list of all matches. The finditer function returns an iterator that allows iterating over each Match object found and accessing the start and end indexes of each match. Both methods allow finding all matches of a pattern in a string, unlike re.search which only returns the first match.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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

silly_string = "the cat in the hat"


pattern = "the"

for match in re.finditer(pattern, silly_string):

s = "Found '{group}' at {begin}:{end}".format(


group=match.group(), begin=match.start(),
end=match.end())
print(s)

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.

You might also like