How to use the re.findall() function to find all matching substrings in a string?
Published on Aug. 22, 2023, 12:18 p.m.
To use the re.findall()
function in Python to find all matching substrings in a string using regex, you can pass a regular expression pattern as the first argument to re.findall()
, and the target string as the second argument. For example:
import re
pattern = r'\d+' # regex pattern to match one or more digits
text = 'I have 3 apples and 2 oranges'
matches = re.findall(pattern, text)
print(matches) # Output: ['3', '2']
This will return a list of all the non-overlapping matches of the regex pattern in the given string. In this case, the regex pattern \d+
matches one or more digits in the text, so the output will be ['3', '2']
. You can modify the regex pattern to match different types of substrings in the string.