【问题标题】:A regex in python for matching multiple lines of certain patternpython中用于匹配特定模式的多行的正则表达式
【发布时间】:2017-02-05 06:19:51
【问题描述】:

您好,我正在尝试构建一个多行正则表达式来分组一行,然后是至少以一个空格开头的行。例如

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 和它的子命令到另一个组。换句话说,以非空格字符开头的行应该与以空格开头的行分组,如果后面跟着行。以非空白字符开头的两行应该是两个不同的组。

我尝试了一些已经讨论过的正则表达式,但这没有帮助。

提前致谢

【问题讨论】:

  • 也许可以尝试不使用正则表达式 - 逐行。

标签: python regex multiline


【解决方案1】:
>>> 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']

【讨论】:

  • 感谢一百万,正是我一直在寻找的。​​span>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-13
  • 1970-01-01
  • 2021-12-02
相关资源
最近更新 更多