Python re.finditer() Method
re.finditer() is a function in the Python re module used toIterate over all matches.
It returns an iterator whose elements are match objects, so each match can be processed one at a time.
Word meaning: find iter means "find iterator".
Basic syntax and parameters
Syntax format
re.finditer(pattern, string, flags=0)
Parameter Description
- pattern: The regular expression pattern
- string: The string to search
- flags: Optional, regular expression flags
Function description
- Return Value: Returns an iterator whose elements are match objects.
- Feature: Suitable for handling a large number of matches, saving memory.
Example
Example 1: basic usage
Example
import
re
text
=
"3 apples, 5 oranges, 8 bananas"
Iteratively find all numbers
for
match
in
re
.
finditer
(
r
'\d+'
,
text
)
:
(
f
"Found: {match.group()} position: {match.start()}-{match.end()}"
)
Expected output:
找到: 3 位置: 0-1
找到: 5 位置: 4-5
找到: 8 位置: 8-9
Example 2: process a list of emails
Example
import
re
text
=
"Contact test@example.com or admin@test.org for help"
Find and process each email
for
match
in
re
.
finditer
(
r
'(\w+)@(\w+.\w+)'
,
text
)
:
(
f
"Full: {match.group()}"
)
(
f
" Username: {match.group(1)}"
)
(
f
" Domain: {match.group(2)}"
)
(
f
" Position: {match.start()}-{match.end()}"
)
Expected output:
完整: test@example.com
用户名: test
域名: example.com
位置: 2-16
完整: admin@test.org
用户名: admin
域名: test.org
位置: 17-30
Example 3: comparison with re.findall()
Example
import
re
text
=
"a1b2c3d4"
findall returns a list of strings
(
"findall:"
,
re
.
findall
(
r
'\d'
,
text
)
)
finditer returns an iterator
(
"finditer:"
,
[
m.
group
(
)
for
m
in
re
.
finditer
(
r
'\d'
,
text
)
]
)
Expected output:
findall: ['1', '2', '3', '4']
finditer: ['1', '2', '3', '4']
Python re Module