Python Regex finditer()

Summary: in this tutorial, you’ll learn how to use the Python regex finditer() function to find all matches in a string and return an iterator that yields match objects.

Introduction to the Python regex finditer function

The finditer() function matches a pattern in a string and returns an iterator that yields the Match objects of all non-overlapping matches.

The following shows the syntax of the finditer() function:

re.finditer(pattern, string, flags=0)Code language: Python (python)

In this syntax:

  • pattern is regular expression that you want to search for in the string.
  • string is the input string.
  • flags parameter is optional and defaults to zero. The flags parameter accepts one or more regex flags. The flags parameter changes how the regex engine matches the pattern.

If the search is successful, the finditer() function returns an iterator yielding the Match objects. Otherwise, the finditer() also returns an iterator that will yield no Match object.

Python regex finditer example

The following example uses the finditer() function to search for all vowels in a string:

import re

s = 'Readability counts.'
pattern = r'[aeoui]'

matches = re.finditer(pattern, s)
for match in matches:
    print(match)Code language: Python (python)

Output:

<re.Match object; span=(1, 2), match='e'>
<re.Match object; span=(2, 3), match='a'>
<re.Match object; span=(4, 5), match='a'>
<re.Match object; span=(6, 7), match='i'>
<re.Match object; span=(8, 9), match='i'>
<re.Match object; span=(13, 14), match='o'>
<re.Match object; span=(14, 15), match='u'>Code language: Python (python)

Summary

  • Use the finditer() function to match a pattern in a string and return an iterator yielding the Match objects.
Did you find this tutorial helpful ?