The finditer method in Python regular expressions
The finditer method is designed to get an iterator of all matches with a regular expression in a string. In the first parameter of the method, we specify the regular expression we will search for, in the second parameter - the string we are searching for. The method checks all matches, searching for them from left to right. The method returns an iterator of matching objects. The syntax of the finditer method looks like this:
re.finditer(what to look for, where to look)
Let's find all substrings with numbers in our string:
txt = 'aaaa 123 bbbb 456'
print(re.finditer('\d+', txt))
Result of code execution:
<callable_iterator object at 0x000002AA891300A0>
Now let's declare a variable res, whose value will be the object we got in the previous example. Then we'll loop over it:
txt = 'aaaa 123 bbbb 456'
res = re.finditer('\d+', txt)
for el in res:
print(el)
After executing the code, two match objects will be output:
<re.Match object; span=(5, 8), match='123'>
<re.Match object; span=(14, 17), match='456'>
These objects contain information about all matches with a regular expression in the form of a tuple. You can derive matches from them by index:
for el in res:
print(el[0])
Result of code execution:
'123'
'456'
Given a string:
txt = '12 aaa 34 bbb 56 ccc'
Output all numbers from it using a loop.