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

Python正则利用反向引用匹配重复子组实现指定格式字符串替换的问题

解决方案

核心逻辑使用正则反向引用实现前后数字一致性校验:正则模式中\数字语法可直接引用对应顺序捕获组匹配到的内容,确保前后两个N完全相同。

针对11000的数字范围约束,捕获组规则设计为`([1-9]\d{0,2}|1000)`,可覆盖1999和1000的所有合法取值。

完整可运行代码如下:

import re

# 匹配模式,加re.IGNORECASE兼容document大小写差异
match_pattern = r'([1-9]\d{0,2}|1000)(\s?)\.(\s+)\[document \1\]'
replace_pattern = r'\1\2.\3'

# 测试合法匹配场景
test_str1 = "whatever whatever 1. [document 1] This is a document dealing with"
result1 = re.sub(match_pattern, replace_pattern, test_str1, flags=re.IGNORECASE)
print(result1)
# 输出:whatever whatever 1. This is a document dealing with

# 测试不匹配场景(前后数字不同,不会触发替换)
test_str2 = "whatever whatever 56. [document 877] This is a document dealing with"
result2 = re.sub(match_pattern, replace_pattern, test_str2, flags=re.IGNORECASE)
print(result2)
# 输出:whatever whatever 56. [document 877] This is a document dealing with

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 22:24:02