正则匹配时如何仅提取匹配结果的指定部分 避免捕获多余等号字符
问题原因
你写的正则将等号字符放在了捕获分组的范围内,所以捕获结果会自动带上等号,无法直接得到纯数字结果。
解决方案
使用非捕获分组(?: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
相关产品推荐
相关产品推荐

