繁体   English   中英

python中的正则表达式,用于匹配特定模式的多行

[英]A regex in python for matching multiple lines of certain pattern

嗨,我正在尝试构建多行正则表达式,以对一行进行分组,然后再以至少一个空格开头的行进行分组。 例如

interface Ethernet 1/1

      ip address <>
      mtu <>

ip tcp path-mtu-discovery

router bgp 100

     network 1.1.1.0

如何构建将“ interface ethertnet 1/1”及其子配置归为一组,并将“ ip tcp path-mtu-discovery”归为另一组,并将bgp及其子命令归为另一组的正则表达式。 换句话说,以非空白字符开头的行应与以空白开头的行进行分组(如果后面紧跟)。 以非空白字符开头的两行应该是两个不同的组。

我尝试了一些已经讨论过的正则表达式,但这无济于事。

提前致谢

>>> lines = '''interface Ethernet 1/1
...
...       ip address <>
...       mtu <>
...
... ip tcp path-mtu-discovery
...
... router bgp 100
...
...      network 1.1.1.0
... '''
>>> for x in re.findall(r'^\S.*(?:\n(?:[ \t].*|$))*', lines, flags=re.MULTILINE):
...     print(repr(x))
...
'interface Ethernet 1/1\n\n      ip address <>\n      mtu <>\n'
'ip tcp path-mtu-discovery\n'
'router bgp 100\n\n     network 1.1.1.0\n'
  • ^\\S.+ :匹配以非空格字符开头的行。
  • \\n[ \\t].* :匹配以空格字符开头的行。
  • \\n$ :匹配空行
  • \\n(?:[ \\t].*|$) :匹配以空格开头的行或( | )空行

使用itertools.groupby

lines = '''interface Ethernet 1/1

      ip address <>
      mtu <>

ip tcp path-mtu-discovery

router bgp 100

     network 1.1.1.0
'''

class LineState:
    def __init__(self):
        self.state = 0
    def __call__(self, line):
        # According to the return value of this
        # method, lines are grouped; lines of same values are
        # grouped together.
        if line and not line[0].isspace():
            # Change state on new config section
            self.state += 1
        return self.state

import itertools
for _, group in itertools.groupby(lines.splitlines(), key=LineState()):
    print(list(group))

印刷品:

['interface Ethernet 1/1', '', '      ip address <>', '      mtu <>', '']
['ip tcp path-mtu-discovery', '']
['router bgp 100', '', '     network 1.1.1.0']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM