3. Find all
re.findall() returns every non-overlapping match in a list:
pattern,stringandflagsmean the same as inre.search().- With no groups, the list contains the matched text as strings:
re.findall("cat", "cat dog cat")→['cat', 'cat']. - With one group, each list item is the text of that group, not the whole match.
- With several groups, each item is a tuple of the groups, in order.
- If nothing matches, the result is an empty list
[].
len(matches) counts how many matches were found.
Unlike search(), findall() never returns match objects: it returns plain strings or tuples, so you cannot call .start() on its items.
Coming from JavaScript? re.findall is close to text.match(/.../g), but Python returns only the captured groups when the pattern has parentheses, while JS match with g returns whole matches.
Find every match
Import re and call re.findall() with the pattern "Python" and the text "Python is fun. Python is fast.". Print the list it returns.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Count the matches
Use the same pattern "Python" and text "Python is fun. Python is fast.". Store the result of re.findall() in a variable and print its length with len().
Print exactly:
Create a free account to save your progress and unlock chapter 2.
A group changes the result
With one group, re.findall() returns the captured text instead of the whole match. Use the pattern r"id:(7)" on "id:7 id:7" and print the list.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Several groups return tuples
With several groups, each list item is a tuple of the groups. Use the pattern r"(cat) (dog)" on "cat dog cat dog" and print the list.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
No match returns an empty list
Search for "dog" in "cat" with re.findall(). When there is no match, the result is an empty list.
Print exactly:
Create a free account to save your progress and unlock chapter 2.