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

Python正则替换问题:仅替换第一个[]中逗号后的数字范围

问题描述

有两个字符串phase_x和phase_y,需求是仅替换第一个[]之后的那个[]内、第一个逗号后的数字范围(例如phase_x里的24 to 34、phase_y里的1 to 3)为指定范围10 to 20。但当前代码处理phase_x时错误替换了[Ego:]后的数字范围,phase_y看似正常,需要修正这个问题。

原代码
import os
import random
import re

phase_x = "PHASE 1: [Drive_Towards] [-, 24 to 34, -4 to -3][Ego: -10 to 0, FSR]"
phase_y = "PHASE 1: [Walk_Towards] [-, 1 to 3, -3 to -5][Ego:-4 to -2, FSL]"
LowerValue = 10
HigherValue = 20

myRegex_1 = "\d+\sto\s\d+"
myRegex_2 = str(LowerValue)+" to "+ str(HigherValue)

new_line_phase_x = re.sub(myRegex_1, myRegex_2, phase_x)
new_line_phase_y = re.sub(myRegex_1, myRegex_2, phase_y)

print(new_line_phase_x)
print(new_line_phase_y)
问题原因

原正则\d+\sto\s\d+仅匹配由正整数组成的数字范围:

  • phase_y里[Ego:-4 to -2的数字是负数,\d+无法匹配开头的负号,所以这个范围没被替换,看起来“正常”;
  • phase_x里[Ego: -10 to 0的10是正整数,正则匹配到了10 to 0,所以错误替换了这个位置的内容。
    同时,原正则会替换所有符合格式的数字范围,没有限定只替换目标位置的内容。
解决方法

需要编写更精准的正则,定位到目标位置(第二个[]内、第一个逗号后的数字范围),只替换该位置的内容。可以使用正向预查和限定匹配范围来实现:

import re

phase_x = "PHASE 1: [Drive_Towards] [-, 24 to 34, -4 to -3][Ego: -10 to 0, FSR]"
phase_y = "PHASE 1: [Walk_Towards] [-, 1 to 3, -3 to -5][Ego:-4 to -2, FSL]"
LowerValue = 10
HigherValue = 20

# 正则解释:
# (?<=\[-,\s) 正向预查,匹配前面是 "[-, " 的位置
# \d+\s+to\s+\d+ 匹配目标数字范围
# (?=,.*?]) 正向预查,匹配后面是 ", ... ]" 的位置,确保在目标[]内
target_regex = r"(?<=\[-,\s)\d+\s+to\s+\d+(?=,.*?])"
replace_str = f"{LowerValue} to {HigherValue}"

new_line_phase_x = re.sub(target_regex, replace_str, phase_x)
new_line_phase_y = re.sub(target_regex, replace_str, phase_y)

print(new_line_phase_x)
# 输出:PHASE 1: [Drive_Towards] [-, 10 to 20, -4 to -3][Ego: -10 to 0, FSR]
print(new_line_phase_y)
# 输出:PHASE 1: [Walk_Towards] [-, 10 to 20, -3 to -5][Ego:-4 to -2, FSL]

如果需要兼容可能的空格差异(比如[-, 24 to 34多个空格),可以把正则里的\s改成\s*匹配任意空格:

target_regex = r"(?<=\[-,\s*)\d+\s+to\s+\d+(?=\s*,.*?])"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 14:24:18