簡體   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