如何用正则表达式提取路由器show interface输出每行首个字符串?
解析路由器show interface输出提取接口名的解决方案
针对你要提取路由器show interface输出中每行首个空格前的接口描述符需求,这里给出可行的解决方法:
问题分析
你之前的正则表达式r'\w+*\w*|\w**\w+'存在两个核心问题:
- 语法错误:
\w+*和\w**属于无效的正则语法,*是量词,不能直接跟在另一个量词+后面 - 匹配范围不全:接口名包含
/字符,但\w仅匹配字母、数字和下划线,无法覆盖/
正确的正则表达式与Python实现
要匹配每行开头到第一个空格的所有非空白字符,可以用以下两种方案:
方案1:精准匹配接口名允许的字符
接口名通常包含字母、数字和/,可以直接指定匹配范围:
import re output = """Ethernet0/0 10.10.10.103 YES DHCP up up GigabitEthernet0/1 unassigned YES manual administratively down down Ethernet0/2 unassigned YES manual administratively down down Ethernet0/3 unassigned YES manual administratively down down""" # 匹配行开头的字母、数字、/组合 interfaces = re.findall(r'^[\w/]+', output, re.MULTILINE) print(interfaces)
方案2:匹配所有非空白字符(更通用)
如果接口名可能包含其他特殊字符,直接匹配行开头的所有非空白字符更稳妥:
import re output = """Ethernet0/0 10.10.10.103 YES DHCP up up GigabitEthernet0/1 unassigned YES manual administratively down down Ethernet0/2 unassigned YES manual administratively down down Ethernet0/3 unassigned YES manual administratively down down""" # 匹配行开头到第一个空格的所有非空白字符 interfaces = re.findall(r'^[^\s]+', output, re.MULTILINE) print(interfaces)
两种方案的输出结果均为:
['Ethernet0/0', 'GigabitEthernet0/1', 'Ethernet0/2', 'Ethernet0/3']
关键注意点:必须添加re.MULTILINE标志,让^匹配每行的开头,而不是整个字符串的开头。
内容的提问来源于stack exchange,提问作者Jt.netcompute
相关产品推荐
相关产品推荐

