我有2行作为命令输出sh ip int bri
,我想获取所有接口。我的表达式匹配一行具有FastEthernet0 / 0但不是loopback0的行。任何建议请。
line
'Loopback0 1.1.1.1是NVRAM up up'
line1
'FastEthernet0 / 0 10.0.0.1是NVRAM up up'
match=re.search(r'\w+\d+?/?\d+?\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s+\w+\s+\w+\s+(up|down)\s+(up|down)', line1)
match.group()
'FastEthernet0 / 0 10.0.0.1是NVRAM up up'
match=re.search(r'\w+\d+?/?\d+?\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s+\w+\s+\w+\s+(up|down)\s+(up|down)', line)
match.group()
追踪(最近一次通话): 文件“”,第1行,in match.group() AttributeError:'NoneType'对象没有属性'group'
答案 0 :(得分:1)
您正在寻找的非常详细的版本(使用命名组(?P<name>regex)
可以轻松访问匹配项):
import re
re_str = '''
(?P<name>[\w/]+) # the name (alphanum + _ + /)
\s+ # one or more spaces
(?P<IP>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) # IP address
\s+ # one or more spaces
(?P<yesno>YES|NO) # yes (or no?)
\s+ # one or more spaces
(?P<type>\w+) # type (?)
\s+ # one or more spaces
(up|down) # up (or down?)
\s+ # one or more spaces
(up|down) # up (or down?)
'''
regex = re.compile(re_str, flags=re.VERBOSE)
text = '''Loopback0 1.1.1.1 YES NVRAM up up
FastEthernet0/0 10.0.0.1 YES NVRAM up up
FastEthernet0/0 10.0.0.1 YES NVRAM up up'''
for line in text.split('\n'):
match = regex.match(line)
print(match.group('name'), match.group('IP'))
打印
Loopback0 1.1.1.1
FastEthernet0/0 10.0.0.1
FastEthernet0/0 10.0.0.1