findall method in python regular expressions
To find all matches with a regular expression in Python, the findall method is used. In the first parameter of the method, we specify the regular expression we will search for, in the second parameter - the string to search for. The method checks all matches, searching for them from left to right. It returns a list of strings with matches or a list of tuples if the search specifies regular expressions in pockets. If no matches are found, an empty list is returned. The syntax of the findall method looks like this:
re.findall(what to look for, where to look)
Let's find all matches with a regular expression in a string:
txt = '12 43 56 ab'
res = re.findall('\d+', txt)
print(res)
Result of code execution:
['12', '43', '56']
Given a string:
txt = '123 aaa 456 bbb 789'
Print a list of substrings containing numbers.
Given a string:
txt = 'abc 123 def 456 789'
Print a list of substrings containing letters.