You need to enable JavaScript to run this app. Python使用正则表达式匹配空格开头行及提取配置块的方法
优惠活动
大模型
产品
解决方案
定价
更多

Python使用正则表达式匹配空格开头行及提取配置块的方法

思科配置line con 0块提取实现方案

你的原有正则存在3个核心问题:

  1. 没有严格匹配line con 0的完整行首标识,容易匹配到其他包含line con的冗余内容
  2. 前瞻条件没有开启多行模式,无法正确识别下一个非缩进的配置行边界
  3. 匹配规则没有对齐思科配置的缩进特征,边界判定逻辑错误

方案1:正则实现

正确的正则需要同时开启多行模式(re.M)和单行模式(re.S),匹配规则为从行首的line con 0开始,匹配到下一个行首非空格的配置行为止:

import re

config_text = """
!
line con 0
 session-timeout 5 
 exec-timeout 5 0
 password 7 1239211A43054F0202D1D
 transport output none
line 2
 no activation-character
 no exec
 transport preferred none
 transport output pad telnet rlogin lapb-ta mop udptn v120 ssh
 stopbits 1
line vty 0 4
 session-timeout 5 
 access-class 125 in
 exec-timeout 5 0
 length 0
 transport input ssh
 transport output none
"""

result = re.findall(r'^line con 0.*?(?=\n\S)', config_text, flags=re.M|re.S)
if result:
    print(result[0].strip())

输出结果完全符合预期:

line con 0
 session-timeout 5 
 exec-timeout 5 0
 password 7 1239211A43054F0202D1D
 transport output none

方案2:逐行遍历实现(容错性更高)

如果配置格式存在波动(比如有注释、空行),逐行判定的方式稳定性更强:

def extract_con0_block(config):
    lines = config.splitlines()
    capture = False
    res = []
    for line in lines:
        if line.strip() == "line con 0":
            capture = True
            res.append(line)
            continue
        if capture:
            # 遇到非缩进的新配置行就停止捕获
            if line and not line.startswith((' ', '\t')):
                break
            res.append(line)
    return '\n'.join(res).strip()

print(extract_con0_block(config_text))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 23:06:05