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

如何在Python中用正则表达式替换JSON中的指定URL片段

解决JSON中特定URL的替换问题

方法1:解析JSON字典处理(更安全)

这种方法先把JSON解析为Python字典,针对性处理每个值,避免破坏JSON结构:

import json
import re

# 读取目标JSON文件
with open('target.json', 'r', encoding='utf-8') as f:
    json_data = json.load(f)

# 定义匹配规则和替换模板
match_pattern = r'(https://)foo(\.bar\.com/x/)env_t(/.*)'
replace_str = r'\1fooa\2env_a\3'

# 遍历字典,处理符合格式的URL
for key, val in json_data.items():
    if isinstance(val, str) and re.match(r'https://foo\.bar\.com/x/env_t/', val):
        json_data[key] = re.sub(match_pattern, replace_str, val)

# 写入修改后的JSON
with open('modified_target.json', 'w', encoding='utf-8') as f:
    json.dump(json_data, f, indent=2)

方法2:直接对JSON字符串正则替换

如果不想解析字典,也可以直接对JSON字符串做替换,注意正则要精准匹配目标URL:

import re

# 读取JSON内容(或从文件读取)
raw_json = '''{
 "a_url": "https://foo.bar.com/x/env_t/xyz?asd=dfg",
 "b_url": "https://foo.bar.com/x/env_t/xyz?asd=dfg",
 "some other property": "blabla",
 "more stuff": "yep",
 "c_url": "https://blabla.com/somethingsomething?maybe=yes"
}'''

# 正则匹配目标URL并替换
pattern = r'(https://)foo(\.bar\.com/x/)env_t(/[^"]+)'
modified_json = re.sub(pattern, r'\1fooa\2env_a\3', raw_json)

# 输出或保存结果
print(modified_json)

正则说明

  • 分组\1捕获https://,\2捕获.bar.com/x/,\3捕获env_t之后到引号前的所有内容
  • 替换时仅修改foo为fooa、env_t为env_a,其余部分保持不变
  • 原正则中的\"是HTML转义的引号,在Python中无需保留,调整后的正则更精准,不会误匹配其他内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 16:45:44