2016-04-11 38 views
-1

圖像鏈接here。 我有以下的路由器輸出:簡單的Python正則表達式來分隔單詞

config t 
Enter configuration commands, one per line. End with CNTL/Z. 
n7k(config)# port-profile demo_ethernet 
n7k(config-port-prof)# ? 
    bandwidth  Set bandwidth informational parameter 
    beacon   Disable/enable the beacon for an interface 
    cdp    Configure CDP interface parameters 
    channel-group Configure port channel parameters 
    delay   Specify interface throughput delay 
    description  Enter port-profile description of maximum 80 characters 

從上面的輸出,我想這一點:

['bandwidth' , 'beacon' , 'cdp' , 'channel-group' , 'delay' , 'description'] 

我想

m = re.compile('(\w+\s\w+)') 
n = m.findall(buffer) 

並得到這樣的輸出:

['config t', 'Enter configuration', 'one per', 'End with', 'profile demo_ethernet', 'Set bandwidth', 'informational parameter', 'enable the', 'beacon for', 'an interface', 'Configure CDP', 'interface parameters', 'Configure port', 'channel parameters', 'Specify interface', 'throughput delay', 'Enter port', 'profile description', 'of maximum', '80 characters'] 
+0

匹配的規則是什麼? –

+0

我想要左側的按鍵。並在第一個四行後。 – ursandy

+0

請正確格式化您的數據。它顯示爲一個長字符串。 –

回答

0

This reg前應該工作(假設你想要的任何行匹配在出發空間)

^\s+([\w-]+)\s+.+$ 

Regex Demo

Python代碼(爲簡單起見,我已採​​取了所有輸入一個字符串)

p = re.compile(r'^\s+([\w-]+)\s+.+$', re.MULTILINE) 
test_str = "config t\nEnter configuration commands, one per line. End with CNTL/Z.\nn7k(config)# port-profile demo_ethernet\nn7k(config-port-prof)# ?\n bandwidth  Set bandwidth informational parameter\n beacon   Disable/enable the beacon for an interface\n cdp    Configure CDP interface parameters\n channel-group Configure port channel parameters\n delay   Specify interface throughput delay\n description  Enter port-profile description of maximum 80 characters" 

print(re.findall(p, test_str)) 

Ideone Demo

+0

@ursandy這個'regex'是否符合您的要求? – rock321987

+0

是的。謝謝。 @ rock321987。 – ursandy

+0

已接受。 但爲什麼我的問題被評爲-1? – ursandy