When using regular expressions in Python, the match method of a compiled regex object will return a Match object if there is a match, or None otherwise. However, if you want to find multiple matches in a string, you should use the findall method instead of match. The findall method returns a list of all non-overlapping matches in the string.

Here's an example of how to use the findall method to extract all occurrences of a pattern in a string:

python
import re pattern = r'\d+' # a regex pattern that matches one or more digits text = 'I have 3 apples and 5 bananas, and you have 2 oranges.' matches = re.findall(pattern, text) # returns a list of all digit strings found in text print(matches) # prints ['3', '5', '2']

In this example, the regex pattern \d+ matches one or more digits, and the findall method is used to extract all digit strings in the text string. The resulting list of matches is then printed.

Note that findall returns a list of strings, even if the regex pattern has groups. Each element in the list is the string that matches the entire pattern or a specific group within the pattern, depending on how the pattern is defined.

Have questions or queries?
Get in Touch