2016-04-11 91 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