re.search来获取所有子块。

问题描述 投票:0回答:1

我遇到了一个关于块的regex的问题。我试图匹配块中的一个值。当我使用re.search来匹配接口块中的所有实例时,每次都以 "instance 3 "结束。 我如何获取该块中所有的实例行和值?

代码是这样的

for instance in serviceList:
   serviceData = re.search('('+instance+'.*?\n)+\sinstance',block,re.DOTALL)

输入:

interface
 description 
 mtu 1992
 instance 1
  description OMCH Global Table 
  encapsulation dot1q 1100 second-dot1q 101
 !
 instance 2
  description UNENCRYPT
  bridge-domain 132
 !
 instance 3
  description ENCRYPT
 !
 instance 4
  description TEF
 !
!
python regex search
1个回答
0
投票
extract = re.search("instance \d+.*!", block, re.DOTALL).group().split("instance")

for i, j in enumerate(extract):
    if j:
        print("instance" + j)
        print('**' * 10)

輸出

instance 1
  description OMCH Global Table 
  encapsulation dot1q 1100 second-dot1q 101
 !

********************
instance 2
  description UNENCRYPT
  bridge-domain 132
 !

********************
instance 3
  description ENCRYPT
 !

********************
instance 4
  description TEF
 !
!
********************

0
投票

对于第4个实例来说,这并不可行,因为你希望regex也能在最后匹配一个实例。最后一个(第4个)实例不以 "instance "结尾。

如果你使用 ! 作为定界符,那么你可以做这样的事情---。

import re
my_re = r'(?P<instance_id>instance\s\d+)(?P<contents>[^!]*)'
my_input = '''
interface
 description
 mtu 1992
 instance 1
  description OMCH Global Table
  encapsulation dot1q 1100 second-dot1q 101
 !
 instance 2
  description UNENCRYPT
  bridge-domain 132
 !
 instance 3
  description ENCRYPT
 !
 instance 4
  description TEF
 !
!
'''

# create a map of instance id to contents
instance_to_contents = {}
for instance_id, contents in re.findall(my_re, my_input, flags=re.DOTALL):
    instance_to_contents[instance_id] = contents


serviceList = ['instance 1', 'instance 2', 'instance 3', 'instance 4']
# look them up
for instance in serviceList:
    print(instance_to_contents[instance])

或者,如果你不想在一开始就为所有的人创建一个地图(如果输入的数据太大,你只需要搜索几个实例),你可以在for循环中创建regex。

serviceList = ['instance 1', 'instance 2', 'instance 3', 'instance 4']
# look them up
for instance in serviceList:
    my_re = instance + '(?P<contents>[^!]*)'
    print(re.findall(my_re, my_input, flags=re.DOTALL))
© www.soinside.com 2019 - 2024. All rights reserved.