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

Python正则:替换配对花括号内所有\"为",而非仅最后一处

解决Python中仅替换配对花括号内指定字符串的问题

核心方案

先精准匹配配对花括号{}内的完整内容,再对每个匹配结果内部批量替换目标字符串,同时自动排除不配对的花括号场景。

代码实现

import re

# 原始场景字符串
original_str = r'Here is my string with "\"The Address\", I want to replace only the selection between the brackes: {Here is my string between \"The Address\" and \"something\" else}. Thank you!'

# 补充场景字符串(含不配对花括号)
supplement_str = r'Here is my string with "\"The Address\", I want to replace} only the selection between the brackes: {Here is my string between \"The Address\" and \"something\" else}. Thank you!'

# 定义替换逻辑:匹配配对花括号内的内容,再替换内部的目标字符串
def replace_inside_braces(match):
    # 取出花括号内的内容,替换所有 \" 为 "
    return match.group().replace(r'\"', '"')

# 执行替换
result1 = re.sub(r'\{[^{}]*\}', replace_inside_braces, original_str)
result2 = re.sub(r'\{[^{}]*\}', replace_inside_braces, supplement_str)

# 输出结果
print("原始场景处理后:")
print(result1)
print("\n补充场景处理后:")
print(result2)

关键细节说明

  1. 正则匹配逻辑:r'\{[^{}]*\}' 确保只匹配配对且无嵌套的花括号内容:
    • \{ 匹配左花括号
    • [^{}]* 匹配任意非花括号的字符(避免跨不配对的花括号)
    • \} 匹配右花括号
  2. 批量替换实现:通过re.sub的回调函数,对每个匹配到的花括号内容单独处理,一次性替换内部所有\",解决了你之前正则只能替换最后一处的问题。
  3. 不配对花括号排除:因为正则要求从{开始到对应的}结束,补充场景中前面的单独}不会被匹配,自然不会误替换其附近的字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:50:24