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

Python字符串子串查找替换:正则匹配范围受限问题求解

嘿,我明白你的问题了——你现在的正则只能精准匹配total=5或者total =5这类固定数字的情况,自然没法覆盖其他带不同数字的total=X格式。下面给你调整方案:

解决方案:修改正则匹配任意数字序列

核心就是把写死的数字5改成能匹配任意数字组合的正则规则,这样就能批量替换所有符合total=数字或total = 数字格式的子串了。

修改后的正则说明

把原来的r"total\s?=\s?5"替换成r"total\s?=\s?\d+",各部分的作用:

  • total:精准匹配"total"字符串
  • \s?:匹配0个或1个空格(兼容有没有空格的两种写法:total=和total =)
  • =:匹配等号本身
  • \d+:匹配1个或多个数字(覆盖所有整数数字的情况,比如5、15、9都能命中)

完整可运行代码

import re

strings = [ 
    "On monday we had total=5 cars", 
    "On tuesday we had total = 15 cars", 
    "On wednesday we are going to have total=9 or maybe less cars" 
]
new_total = "total = 20"

for str in strings:
    # 用新正则批量替换所有符合格式的子串
    new_string = re.sub(r"total\s?=\s?\d+", new_total, str)
    print(new_string)

运行效果

执行后会输出:

On monday we had total = 20 cars
On tuesday we had total = 20 cars
On wednesday we are going to have total = 20 or maybe less cars

这样不管原来的total后面跟的是哪个数字,都会被统一替换成你指定的new_total内容啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:11:23