如何提取所有平衡括号组内的内容(包含嵌套括号场景)
问题原因
你当前使用的正则表达式无法满足需求的核心原因是:传统正则表达式没有计数能力,无法处理任意深度的括号嵌套场景。你写的非贪婪匹配规则(.+?)遇到嵌套括号时,会匹配到第一个右括号就停止,比如处理xx(aa(bb))xx时,只会提取到aa(bb,完全不符合预期。
正确实现方案
使用栈结构统计括号的匹配状态,遍历字符串的同时记录括号的起止位置,就能提取所有层级的平衡括号内容,支持任意深度的嵌套场景。
实现代码
def extract_balanced_parentheses(s): stack = [] result = [] for idx, char in enumerate(s): if char == '(': # 左括号入栈,记录当前索引位置 stack.append(idx) elif char == ')' and stack: # 匹配到对应右括号,弹出最近的左括号位置 start = stack.pop() # 提取括号内内容,自动去除首尾空白 content = s[start+1:idx].strip() result.append(content) # 若需要外层括号内容在前,改为return tuple(reversed(result))即可 return tuple(result)
测试验证
text1 = 'xx(aa)(bb)xx' print(extract_balanced_parentheses(text1)) # 输出: ('aa', 'bb') text2 = 'xx(aa(bb))xx' # 调整返回顺序为外层在前 def extract_outer_first(s): stack = [] res = [] for idx, c in enumerate(s): if c == '(': stack.append(idx) elif c == ')' and stack: st = stack.pop() res.append(s[st+1:idx].strip()) return tuple(reversed(res)) print(extract_outer_first(text2)) # 输出: ('aa(bb)', 'bb')
内容的提问来源于stack exchange,提问作者Scheinin
相关产品推荐
相关产品推荐

