You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让re.findall与re.finditer执行正则匹配得到相同提取结果?

解决方案

你出现该问题的核心原因是调用group()时没有指定捕获组编号:

  • 你写的正则"(.*?)"中,()包裹的内容是第1个手动标记的捕获组。group()不传参数时默认等价于group(0),会返回整个正则匹配到的完整内容,自然包含前后的双引号
  • 只需把obj.group()改成obj.group(1),就能直接拿到捕获组内不带双引号的内容,无需额外做字符串修剪处理

修改后的完整代码如下:

import re
text = 'This is a very "sweet" and "beautiful" cake.'

all_obj = re.finditer('"(.*?)"', text)
result = []
for obj in all_obj:
    result.append(obj.group(1))
print(result)

运行后输出为['sweet', 'beautiful'],符合预期。

如果你不想使用捕获组,也可以改用零宽断言写法,正则修改为r'(?<=").*?(?=")',此时匹配到的内容本身就不含双引号,直接调用obj.group()也能得到正确结果:

import re
text = 'This is a very "sweet" and "beautiful" cake.'

all_obj = re.finditer(r'(?<=").*?(?=")', text)
result = []
for obj in all_obj:
    result.append(obj.group())
print(result)

内容的提问来源于stack exchange,提问作者user11749375

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 20:06:07