我正在尝试从以下代码中获取2个ipv6地址:
import re
from pprint import pprint
with open('show_ipv6_intf.txt') as f:
show_ipv6_int = f.read()
match = re.search(r'^\s+(\S+)\s\[VALID\]\s+(\S+).*', show_ipv6_int,flags=re.M)
ipv6_1 = match.group(1)
ipv6_2 = match.group(2)
ipv6_list = []
ipv6_list.append(ipv6_1)
ipv6_list.append(ipv6_2)
print(ipv6_list)对于广度,
下面是正在使用的文件:
Ethernet2/4, Interface status: protocol-up/link-up/admin-up, iod: 40
IPv6 address:
2001:11:2233::a1/24 [VALID]
2001:cc11:22bb:0:2ec2:60ff:fe4f:feb2/64
IPv6 subnet: 2001::/24
IPv6 link-local address: fe80::2ec2:60ff:fe4f:feb2 (default) [VALID]
IPv6 virtual addresses configured: none
IPv6 multicast routing: disabled
IPv6 report link local: disabled
IPv6 Forwarding feature: disabled
IPv6 multicast groups locally joined:
ff02::1:ff4f:feb2 ff02::2 ff02::1 ff02::1:ff00:a1
ff02::1:ff4f:feb2 ff02::1:ff00:0
IPv6 multicast (S,G) entries joined: none
IPv6 MTU: 1500 (using link MTU)
IPv6 unicast reverse path forwarding: none
IPv6 load sharing: none
IPv6 interface statistics last reset: never
IPv6 interface RP-traffic statistics: (forwarded/originated/consumed)
Unicast packets: 0/0/0
Unicast bytes: 0/0/0
Multicast packets: 0/18/0
Multicast bytes: 0/2076/0如果我使用"re.M“标志,我会检索所需的结果,但是当我使用"re.DOTALL”时,我会得到"None“布尔值。如下所示:
使用re.M
C:\Users\Kenyone\.PyCharm2019.3\config\scratches>python week4lesson6.py ['2001:11:2233::a1/24', '2001:cc11:22bb:0:2ec2:60ff:fe4f:feb2/64']
使用re.DOTALL
C:\Users\Kenyone\.PyCharm2019.3\config\scratches>python week4lesson6.py Traceback (most recent call last): File "week4lesson6.py", line 7, in <module> ipv6_1 = match.group(1) AttributeError: 'NoneType' object has no attribute 'group'
发布于 2020-09-05 08:01:14
您希望从re.DOTALL中获得什么?它改变了您的正则表达式模式中.的行为,但是您只有一个,而且没有必要。因为它后面跟着*,所以它可以匹配零次。您可以重写模式,而不使用末尾的点星号,并获得相同的行为。
r'^\s+(\S+)\s\[VALID\]\s+(\S+)'应该是相同的,并且没有点。
re.M是必需的,因为您有^,并且希望它在一行的开头匹配,而不仅仅是整个字符串的开头。
您可以同时使用这两个标志,它可以工作,但是re.DOTALL在这里没有做任何有用的事情。
发布于 2020-09-05 08:23:35
如果不使用行断言,则不需要re.M:
[ \t]*([\d:a-f/]+)[ \t]*\[VALID\]\s+([\d:a-f/]+)但这可能会使正则表达式变慢。
使用行断言,速度更快,并且[VALID]两侧的字符类更加具体:
Python demo (将txt设置为示例文本):
>>> reg=re.compile(r'^[ \t]*([\d:a-f/]+)[ \t]*\[VALID\]\s+([\d:a-f/]+)', flags=re.M)
>>> reg.findall(txt)
[('2001:11:2233::a1/24', '2001:cc11:22bb:0:2ec2:60ff:fe4f:feb2/64')]使用您的正则表达式或这个正则表达式,您不需要re.S,它是让.匹配\n的标志。事实上,如果您添加re.S,您的正则表达式将只匹配第一个匹配,因为.*现在将匹配到字符串的末尾:
https://stackoverflow.com/questions/63749125
复制相似问题