在下面的代码中,我想捕获实例ID,然后捕获它下面的主体。这种模式是反复出现的,因此有多个具有相同主体的实例。我似乎想不出如何让它继续通过换行符段。
import re
config = '''
Instance: evpn-a
VLAN ID: 123, MAC address: 00:05:86:71:05:f0
Source: irb.0, Rank: 1, Status: Active
State: <Local-MAC-Only Local-Gateway Remote-Adv-Allowed>
IP address: 192.168.10.251
VLAN ID: 123, MAC address: 00:05:86:71:ab:f0
Source: 20.1.1.2, Rank: 1, Status: Active
State: <Remote-Gateway Local-Adv-Allowed Local-Adv-Done>
IP address: 192.168.10.252
L3 route: 192.168.10.252/32, L3 context: bridge-vrf (irb.0)
Instance: evpn-b
VLAN ID: 123, MAC address: 00:05:86:71:05:f0
Source: irb.0, Rank: 1, Status: Active
State: <Local-MAC-Only Local-Gateway Remote-Adv-Allowed>
IP address: 192.168.10.251
VLAN ID: 123, MAC address: 00:05:86:71:ab:f0
Source: 20.1.1.2, Rank: 1, Status: Active
State: <Remote-Gateway Local-Adv-Allowed Local-Adv-Done>
IP address: 192.168.10.252
L3 route: 192.168.10.252/32, L3 context: bridge-vrf (irb.0)
'''
evpn_obj_list = re.compile(r'Instance:\s+(\S+)(.*?)(?:\S+|\Z)',re.S|re.M).findall(config)
evpn = evpn_obj_list
print(evpn)我从上面得到的结果是:
[('evpn-a', '\n\n'), ('evpn-b', '\n\n')]发布于 2020-07-14 16:16:46
你可以用
rx = re.compile(r'^Instance:\s+(\S+)\s*(.*?)(?=\n\s*Instance:\s|\Z)', re.S|re.M)
evpn_obj_list = rx.findall(config)见regex演示。
详细信息
^ -行的开始Instance: -字符串\s+ - 1+白空间(\S+) - Group 1:任意一个或多个非空白字符\s* - 0+白空间(.*?) -第2组:任意0或多个字符,尽可能少(?=\n\s*Instance:\s|\Z) --一个积极的前瞻性,它需要一个换行符、0+空格、Instance:、一个空格或文件的末尾紧靠在当前位置的右边。见Python演示屈服
[('evpn-a', 'VLAN ID: 123, MAC address: 00:05:86:71:05:f0\n Source: irb.0, Rank: 1, Status: Active\n State: <Local-MAC-Only Local-Gateway Remote-Adv-Allowed>\n IP address: 192.168.10.251\n\nVLAN ID: 123, MAC address: 00:05:86:71:ab:f0\n Source: 20.1.1.2, Rank: 1, Status: Active\n State: <Remote-Gateway Local-Adv-Allowed Local-Adv-Done>\n IP address: 192.168.10.252\n L3 route: 192.168.10.252/32, L3 context: bridge-vrf (irb.0)'), ('evpn-b', 'VLAN ID: 123, MAC address: 00:05:86:71:05:f0\n Source: irb.0, Rank: 1, Status: Active\n State: <Local-MAC-Only Local-Gateway Remote-Adv-Allowed>\n IP address: 192.168.10.251\n\nVLAN ID: 123, MAC address: 00:05:86:71:ab:f0\n Source: 20.1.1.2, Rank: 1, Status: Active\n State: <Remote-Gateway Local-Adv-Allowed Local-Adv-Done>\n IP address: 192.168.10.252\n L3 route: 192.168.10.252/32, L3 context: bridge-vrf (irb.0)\n')]https://stackoverflow.com/questions/62898970
复制相似问题