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

如何使用正则仅匹配line con 0块下的session-timeout 10与exec-timeout 10

思科配置块精准匹配正则方案

问题场景

现有如下配置文本:

line con 0
 session-timeout 10 
 exec-timeout 10 0
 privilege level 15
 logging synchronous
 login authentication console-in
 transport preferred none
 stopbits 1
line vty 0 4
 session-timeout 30 
 exec-timeout 30 0
 logging synchronous
 transport preferred none
 transport input ssh
 transport output ssh
line vty 5 15
 session-timeout 10 
 exec-timeout 10 0
 logging synchronous
 transport preferred none
 transport input ssh
 transport output ssh

需求为仅匹配line con 0配置块下的session-timeout 10和exec-timeout 10两行,原有正则因为贪婪匹配会误命中line vty 5 15块下的同参数行。


原因分析

原有正则使用的.*\n(.*\n)*是贪婪匹配模式,会尽可能向后匹配所有内容,直到找到整个文本中最后一处符合session-timeout 10和exec-timeout 10的位置,自然会跨配置块命中vty段的内容。


解决方案

核心思路

利用负向先行断言限定匹配范围:line con 0块的结束标识是下一行以line 开头的行(即下一个配置块的开始),匹配时禁止跨越这个边界。

可用正则(需开启多行模式)

方案1:捕获组输出结果(兼容大部分正则引擎)

line con 0\n(?:(?!^line ).*\n)*?( session-timeout 10)\s*\n(?:(?!^line ).*\n)*?( exec-timeout 10)

捕获组1对应session-timeout 10行,捕获组2对应exec-timeout 10行。

方案2:直接匹配目标行(支持后发断言/\K语法的引擎可用)

(?<=line con 0\n)(?:(?!^line ).*\n)*?\K session-timeout 10|(?<=line con 0\n(?:(?!^line ).*\n)*? session-timeout 10\n(?:(?!^line ).*\n)*?)\K exec-timeout 10

可直接匹配到两行目标内容,不需要额外提取捕获组。


补充说明

  • 必须开启正则引擎的多行模式(Multiline),保证^可以匹配每一行的行首
  • 所有*?为非贪婪匹配,避免在当前配置块内跳过目标行
  • 若不需要严格匹配空格,可在参数前后加\s*适配多余空格/换行场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 18:48:03