Python Practice › RegEx Programs › Program 19

Match positions with finditer

EasyRegEx Programs · 19 of 20

Write a Python program to print each match of a word with its start and end positions.

Advertisement
Output
python (0, 6)
pytest (11, 17)
pyodide (22, 29)

Approach

  1. finditer gives match objects with span().

Solution

Python
import re for m in re.finditer(r"py\w*", "python and pytest use pyodide"):    print(m.group(), m.span())
Output
python (0, 6)
pytest (11, 17)
pyodide (22, 29)

Learn the concept

New to this topic? Read the lesson, then come back.

More regex programs

← All 20 RegEx Programs

Leave a Comment