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

如何用正则捕获FortiGate中以双end结尾的重复VDOM配置块?

解决FortiGate VDOM配置块提取的正则问题

问题根源

之前尝试的(config vdom\nedit.+\nconfig[\s\S\r]*?end\nend\n\n)出现灾难性回溯,核心原因是惰性匹配[\s\S]*?会在遇到大量嵌套的end时不断回溯尝试匹配,导致性能爆炸甚至报错。

优化后的正则表达式

使用负向预查替代惰性匹配,避免不必要的回溯,精准匹配每个以双end结尾的VDOM块:

(config vdom\nedit .+\n(?:(?!end\nend)[\s\S])*end\nend)

正则各部分说明

  • config vdom\nedit .+:匹配VDOM块的起始行,捕获edit后的VDOM名称行
  • (?:(?!end\nend)[\s\S])*:非捕获组,匹配任意字符(包含换行),直到检测到end\nend为止,负向预查确保不会提前终止
  • end\nend:匹配VDOM块的结尾双end行

Python使用示例

import re

# 读取FortiGate配置文件内容
with open('fortigate_config.conf', 'r') as f:
    config_content = f.read()

# 匹配所有VDOM块
vdom_pattern = re.compile(r'(config vdom\nedit .+\n(?:(?!end\nend)[\s\S])*end\nend)')
vdom_blocks = vdom_pattern.findall(config_content)

# 输出每个VDOM块
for idx, block in enumerate(vdom_blocks, 1):
    print(f"=== VDOM Block {idx} ===")
    print(block)

兼容性调整

如果配置中end行可能包含尾空格(比如end ),可以调整结尾匹配规则,增强兼容性:

(config vdom\nedit .+\n(?:(?!end\s*\nend\s*)[\s\S])*end\s*\nend\s*)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 11:47:28