finditer Yields Matches With Named Spans

Scan a line into structured records with re.finditer: named groups, one-pass iterators that drain, and span positions for surgical edits.

PythonData Integrity

Code

pythonsnippet
26 lines
import re

ENTRY = re.compile(
    r'(?P<level>ERROR|WARN)'      # severity
    r'\s+(?P<code>[A-Z]+-\d+)'    # ticket code
    r'\s+(?P<message>.+?)'        # message: shortest span
    r'(?=\s+(?:ERROR|WARN)\s|$)'  # boundary: next entry or end
)

line = 'ERROR AUTH-401 token expired for user=42 WARN QUOTA-210 api keys 92% used'

# finditer 从左到右扫描,惰性产出 Match 对象
for match in ENTRY.finditer(line):
    fields = match.groupdict()
    print(fields['level'], fields['code'], '|', fields['message'])

# 只扫一遍:消费过的迭代器再次使用是空的
first = ENTRY.finditer(line)
levels = [m.group('level') for m in first]
print('levels  :', levels)
print('consumed:', list(first))

# span 定位 token 的精确位置,便于字符串手术
for match in ENTRY.finditer(line):
    s, e = match.span('code')
    print('span    :', (s, e), repr(line[s:e]))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

ERROR AUTH-401 | token expired for user=42
WARN QUOTA-210 | api keys 92% used
levels  : ['ERROR', 'WARN']
consumed: []
span    : (6, 14) 'AUTH-401'
span    : (46, 55) 'QUOTA-210'

How it works

for match in ENTRY.finditer(line) is the loop that carries the per-item work.

The file’s state is a handful of top-level bindings: line, first, levels.

Putting it to use

The demo output is labeled (levels :, consumed:, span :), so every printed line maps back to its originating operation.

Core lines

for match in ENTRY.finditer(line):
    fields = match.groupdict()
    print(fields['level'], fields['code'], '|', fields['message'])
for match in ENTRY.finditer(line):
    s, e = match.span('code')
    print('span    :', (s, e), repr(line[s:e]))

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. Every import resolves inside the standard library — `re`. Its state lives in module-level bindings: `line`, `first`, `levels`.