首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多重行上的正则表达式\n

多重行上的正则表达式\n
EN

Stack Overflow用户
提问于 2020-07-14 15:47:31
回答 1查看 34关注 0票数 1

在下面的代码中,我想捕获实例ID,然后捕获它下面的主体。这种模式是反复出现的,因此有多个具有相同主体的实例。我似乎想不出如何让它继续通过换行符段。

代码语言:javascript
复制
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)

我从上面得到的结果是:

代码语言:javascript
复制
[('evpn-a', '\n\n'), ('evpn-b', '\n\n')]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-14 16:16:46

你可以用

代码语言:javascript
复制
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演示屈服

代码语言:javascript
复制
[('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')]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62898970

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档