2017-01-02 96 views
0

我有2行作为命令输出sh ip int bri我想获取所有接口。我的重新表达式匹配一个具有FastEthernet0/0但没有loopback0的行。任何建议,请。问题与正则表达式python

line 

'的Loopback0 1.1.1.1 YES NVRAM涨涨'

line1 

'的FastEthernet0/0 10.0.0.1 YES NVRAM涨涨'

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 YES 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() 

T raceback(最后最近一次调用): 文件“”,1号线,在 match.group() AttributeError的:“NoneType”对象有没有属性“组”

+1

可以更新重新向的r \ W + [\ d /] + \ S + \ d {1 ...,3} \ d {1,3} \ d {1,3} \ d {1,3} \ S + \ W + \ S + \ W + \ S +(向上|向下)\ S +(向上|向下)' – Kadir

+0

@Kadir,它的修改如下: - r'\ w + [\ 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) 关于以下错误的任何注释都不起作用: r'\ w + \ d + /?\ d +?\ s +(\ d {1,3} \。){3} \ d {1,3} \ s + \ w + \ s + \ w + \ s +(up | \ s +(up | down)', /?\ d +?和[\ d /] +使差异 –

回答

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