Python如何捕获外层双大括号内部含嵌套大括号的字符串
问题原因
- 第一次使用的正则
\{(.*?)\}采用非贪婪匹配逻辑,遇到第一个}就会终止匹配,刚好命中目标内容里example{''}的右大括号,所以返回的结果不符合预期。 - 第二次修改正则后报错,是因为没有给正则字符串加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
相关产品推荐
相关产品推荐

