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

正则匹配时如何仅提取匹配结果的指定部分 避免捕获多余等号字符

问题原因

你写的正则将等号字符放在了捕获分组的范围内,所以捕获结果会自动带上等号,无法直接得到纯数字结果。

解决方案

使用非捕获分组(?:xxx)包裹不需要提取的等号部分,仅把需要提取的数字放在捕获分组中即可。
修改后的代码如下:

from re import compile, findall

# 非捕获分组包裹等号,仅数字部分放入捕获分组
regex = compile(r'(?:(\d+)=)?\d+\+\d+(?:=(\d+))?')
print(findall(regex, '1+2=3'))
# 输出: [('', '3')]
print(findall(regex, '3=1+2'))
# 输出: [('3', '')]

如果不需要区分结果在等式左侧还是右侧,想要直接拿到结果数字,也可以用零宽断言写法,直接匹配到纯数字结果:

from re import compile, findall

regex = compile(r'(?<=^)\d+(?==\d+\+\d+)|(?<=\d+\+\d+=)\d+(?=$)')
print(findall(regex, '1+2=3'))
# 输出: ['3']
print(findall(regex, '3=1+2'))
# 输出: ['3']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:54:04