Python re.finditer() Method

Python re 模块Python re Module


re.finditer()is a Pythonremodule function foriteratively finding all matches.

It returns an iterator, where each element is a match object, allowing you to process the matching results one by one.

Term Definition: find iterIt means "find iterator".


Basic Syntax and Parameters

Syntax Format

re.finditer(pattern, string, flags=0)

Parameter Description

  • pattern: Regular expression pattern
  • string: The string to be searched
  • flags: Optional, regular expression flags

Function Description

  • Return Value: Returns an iterator, where each element is a match object.
  • Features: Suitable for processing large numbers of match results, saving memory.

Examples

Example 1: Basic Usage

Example

import re

text = "3 apples, 5 oranges, 8 bananas"

# Iterate to 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: Processing Email List

Example

import re

text = "Contact [email protected] or [email protected] 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:

完整: [email protected]
  用户名: test
  域名: example.com
  位置: 2-16
完整: [email protected]
  用户名: 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 模块Python re Module

Other Extensions