101 of 151 menu

The finditer method of re module

The finditer method of the re module returns an iterator of all matches with a regular expression in a string. In the first parameter of the method, we specify the regular expression. In the second parameter, we specify the string in which we are looking for the regular expression. In the third optional parameter, you can specify flags. The method checks all matches, searching for them from left to right.

Syntax

import re re.finditer(regular expression, string, [flags bunting])

Example

Let's find all substrings with numbers in our string:

txt = 'aaaa 123 bbbb 456' res = re.finditer('\d+', txt) print(res)

Result of code execution:

<callable_iterator object at 0x000002AA891300A0>

Example

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 we will get two Match objects:

<re.Match object; span=(5, 8), match='123'> <re.Match object; span=(14, 17), match='456'>

These objects contain information about all matches of the regular expression in the form of a tuple. We can derive matches from them by index:

for el in res: print(el[0])

Result of code execution:

'123' '456'

Example

For greater clarity, let's use pockets when searching for matches. And when iterating over the objects of the cycle, we will output the first match (it will be considered the zero pocket), as well as its elements, which in turn will also be scattered across pockets:

txt = 'aaaa 123 bbbb 456' res = re.finditer('(\d)(\d)', txt) for el in res: print(el[0], el[1], el[2])

After executing the code, we will get the zero pocket, i.e. the entire substring, as well as the first and second characters from this substring:

'12' '1' '2' '45' '4' '5'

See also

  • method findall of module re,
    which returns a list of all matches in a string
  • method search of module re,
    which looks for the first match of a regular expression in a string
  • method match of module re,
    which looks for a match with a regular expression at the beginning of a line
  • method fullmatch of module re,
    which looks for all matches of a regular expression in a string
  • object Match object of module re,
    which contains information about matches with a regular expression
  • method split of module re,
    which splits a string into a list by the specified separator
byenru