您好我正在尝试构建一个多行正则表达式来对一行进行分组,然后是以至少一个空格开头的行。例如
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及其子命令到另一个组。换句话说,以非空格字符开头的行应该与后面的行以空格开头的行进行分组。以非空格字符开头的两行应该是两个不同的组。
我尝试了一些已经讨论过的正则表达式,但这没有用。
提前致谢
答案 0 :(得分: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].*|$)
:匹配以空格开头的行或(|
),空行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']