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

Python使用多组正则提取数值时报错nothing to repeat如何解决

问题根源

+ 是正则表达式的特殊元字符,作用是修饰其前置字符匹配1次及以上。你在匹配阳性次数的正则 '+(\d+)' 中直接使用了未转义的 +,正则解析器找不到该量词对应的修饰对象,就会抛出"nothing to repeat"的语法错误。

解决方案

方案1:修正原有写法

仅需对正则中的+做转义处理即可,同时建议正则前加r声明为原始字符串,避免不必要的转义冲突:

import re
s = "R5+2-3" # 待解析示例字符串
ttl = 0
pos = 0
neg = 0
for matchttl in re.findall(r'R(\d+)', s):
    ttl += int(matchttl)
# 加号转义为\+
for matchpos in re.findall(r'\+(\d+)', s):
    pos += int(matchpos)
for matchneg in re.findall(r'-(\d+)', s):
    neg += int(matchneg)

方案2:更高效的单次匹配写法

可以用一个正则一次性匹配三个字段,无需多次调用findall,性能和可读性更好:
如果单条字符串仅包含一个符合格式的片段:

import re
s = "R5+2-3"
match_res = re.match(r'R(\d+)\+(\d+)-(\d+)', s)
if match_res:
    ttl = int(match_res.group(1))
    pos = int(match_res.group(2))
    neg = int(match_res.group(3))

如果单条字符串包含多个符合格式的片段:

import re
s = "R5+2-3 R10+4-6" # 包含多组数据的示例字符串
ttl = 0
pos = 0
neg = 0
for ttl_str, pos_str, neg_str in re.findall(r'R(\d+)\+(\d+)-(\d+)', s):
    ttl += int(ttl_str)
    pos += int(pos_str)
    neg += int(neg_str)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:18:03