Python多线帮助

时间:2013-12-30 17:15:10

标签: python regex

我希望通过python脚本解析brctl show的输出,但我只是不想绕过多行正则表达式。如果有人可以通过比赛提供比赛,我真的很感激。我觉得我可能在这里遗漏了一些小事。

无论如何,我要做的是采取这样的输出:

bridge name bridge id       STP enabled interfaces
backup      8000.101f7437d7bc   no      eth0
                                        vnet1
                                        vnet10
extra       8000.2c27d750e6a0   no      bond0.142
                                        vnet0
                                        vnet103
                                        vnet106
                                        vnet112
                                        vnet117

创建一个字典interfaces,其中桥名称是键,值是该桥接口的列表,例如:

interfaces[backup]=['eth0', 'vnet1','vnet10']

1 个答案:

答案 0 :(得分:2)

import re

output = '''bridge name bridge id       STP enabled interfaces
backup      8000.101f7437d7bc   no      eth0
                                        vnet1
                                        vnet10
extra       8000.2c27d750e6a0   no      bond0.142
                                        vnet0
                                        vnet103
                                        vnet106
                                        vnet112
                                        vnet117'''
interfaces = {}
for bridge_lines in re.findall(r'(?m)^\S.*\n(?: .*\n)+', output):
    # ^\S.*\n  matches first line that srats with non-space
    #     (backup ... or extra ...)
    # (?: .*\n)+  matches following lines that starts with space.

    bridge, _ = bridge_lines.split(None, 1)
    interfaces[bridge] = re.findall(r'(?m)\S+$', bridge_lines) # Get last fields

print(interfaces['backup'])
print(interfaces['extra'])

输出:

['eth0', 'vnet1', 'vnet10']
['bond0.142', 'vnet0', 'vnet103', 'vnet106', 'vnet112']