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

Python中如何单次匹配带嵌套的起始双花括号对应闭合对?

单次遍历提取嵌套双花括号的匹配闭合部分

完全可以用单次遍历实现,核心思路是用一个计数器追踪双花括号的嵌套层级,具体步骤如下:

  • 初始化一个计数器brace_count,初始值为0
  • 从字符串开头逐个字符遍历:
    • 碰到连续的{{时,计数器加1,同时跳过下一个{避免重复处理
    • 碰到连续的}}时,计数器减1,此时如果计数器回到0,说明找到了最外层的闭合对,直接截取从开头到当前位置(包含这个}})的子串即可
    • 其他字符直接跳过,继续遍历

用Python实现的示例代码如下:

def extract_matching_brace(s):
    brace_count = 0
    idx = 0
    str_len = len(s)
    while idx < str_len:
        if idx + 1 < str_len and s[idx] == '{' and s[idx+1] == '{':
            brace_count += 1
            idx += 2
        elif idx + 1 < str_len and s[idx] == '}' and s[idx+1] == '}':
            brace_count -= 1
            if brace_count == 0:
                return s[:idx+2]
            idx += 2
        else:
            idx += 1
    # 若未找到匹配的闭合对,可根据需求返回原串或None
    return None

# 测试示例字符串
test_str = "{{ABC foo bar {{baz}} {{fred}} foo2}} other text {{other brace pair}}"
print(extract_matching_brace(test_str))

这段代码的时间复杂度是O(n),全程只遍历一次字符串,不管嵌套多少层都能精准定位最外层的闭合对,不会被后续的其他双花括号对干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:55:24