Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python re.finditer() Method

Python re.finditer() Method

Python re Module Python re Module


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

Function description


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

)

:

   

print

(

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

)

:

   

print

(

f

"Full: {match.group()}"

)

   

print

(

f

" Username: {match.group(1)}"

)

   

print

(

f

" Domain: {match.group(2)}"

)

   

print

(

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

print

(

"findall:"

,

re

.

findall

(

r

'\d'

,

text

)

)

finditer returns an iterator

print

(

"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 Python re Module