2017-01-02 50 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