← 中文资源

简体中文版本

findall 返回分组元组而非字符串

单捕获组时 findall 返回字符串列表,两个及以上捕获组就变成元组列表,返回形状随分组数量改变;非捕获组不影响形状,要按名取字段时用 finditer 加 groupdict。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

single group: ['alice', 'bob', 'carol']
two groups:   [('alice', '42'), ('bob', '7'), ('carol', '100')]
non-capturing: ['42', '7', '100']
alice -> 84
bob -> 14
carol -> 200

实现说明

这个示例中仅有的重复出现在 for match in re.finditer(r'(?P<name>\w+)=(?P<score>\d+)', text) 里。 各个操作都建立在顶层绑定之上:text。

使用要点

  • 直接运行文件,输出会带上标签,比如 single group:、two groups:、non-capturing:——输出的每一行都能指回产生它的那次调用。

常见问题

不安装任何包也能运行吗?

可以,开箱即跑——没有引用任何内建 API 之外的东西。 全部导入都来自标准库:re。 状态都挂在模块顶层:text。

核心语句

for match in re.finditer(r'(?P<name>\w+)=(?P<score>\d+)', text):
    info = match.groupdict()
    print(info['name'], '->', int(info['score']) * 2)

代码示例

import re

text = 'alice=42, bob=7, carol=100'

# 单个捕获组:findall 返回字符串列表
print('single group:', re.findall(r'\w+(?==)', text))

# 两个捕获组:findall 返回元组列表,而不是整段匹配文本
print('two groups:  ', re.findall(r'(\w+)=(\d+)', text))

# 非捕获组 (?:...) 不改变返回形状,整体仍是字符串
print('non-capturing:', re.findall(r'(?:\w+)=(\d+)', text))

# 要按名字取字段时,finditer + groupdict 最可读
for match in re.finditer(r'(?P<name>\w+)=(?P<score>\d+)', text):
    info = match.groupdict()
    print(info['name'], '->', int(info['score']) * 2)