Python使用正则表达式匹配空格开头行及提取配置块的方法
思科配置line con 0块提取实现方案
你的原有正则存在3个核心问题:
- 没有严格匹配
line con 0的完整行首标识,容易匹配到其他包含line con的冗余内容 - 前瞻条件没有开启多行模式,无法正确识别下一个非缩进的配置行边界
- 匹配规则没有对齐思科配置的缩进特征,边界判定逻辑错误
方案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
相关产品推荐
相关产品推荐

