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

Python如何捕获外层双大括号内部含嵌套大括号的字符串

问题原因
  1. 第一次使用的正则\{(.*?)\}采用非贪婪匹配逻辑,遇到第一个}就会终止匹配,刚好命中目标内容里example{''}的右大括号,所以返回的结果不符合预期。
  2. 第二次修改正则后报错,是因为没有给正则字符串加Python的原始字符串标识r,转义符\会被Python字符串底层提前解析,导致正则引擎没有按照预期匹配首尾的双大括号,re.search返回None,调用group方法就会触发属性错误。
解决方法

方案1:字符串切片(最简便,适合固定首尾包裹的场景)

如果输入字符串确认固定以{{开头、}}结尾,直接用字符串切片即可,不需要引入正则:

strLine = "{{This a string `` `example{''} with my problem}}"
strLine2 = strLine[2:-2]
print(strLine2)
# 输出:This a string `` `example{''} with my problem

方案2:修正正则表达式

给正则表达式加r前缀标识为原始字符串,避免转义符被提前解析:

import re
strLine = "{{This a string `` `example{''} with my problem}}"
pattern = r"\{\{(.*?)\}\}"
strLine2 = re.search(pattern, strLine).group(1)
print(strLine2)
# 输出:This a string `` `example{''} with my problem

如果要兼容可能不存在首尾双大括号的场景,可以加一层判断避免报错:

import re
strLine = "{{This a string `` `example{''} with my problem}}"
pattern = r"\{\{(.*?)\}\}"
match_res = re.search(pattern, strLine)
if match_res:
    strLine2 = match_res.group(1)
    print(strLine2)
else:
    print("未找到符合要求的内容")

内容的提问来源于stack exchange,提问作者José Mauricio Rodas Rodríguez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:57:01