我正在尝试从下面的行中提取IPV6地址。我得到以下输出..我只是想要IPV6地址,而不是那个。那就是我不想看范围:链接
代码:
out ='ifconfig eth6.36\r\neth6.36 Link encap:Ethernet HWaddr A0:36:9F:5F:24:EE \r\n inet addr:36.36.36.10 Bcast:36.36.36.255 Mask:255.255.255.0\r\n inet6 addr: fe80::a236:9fff:fe5f:24ed/64 Scope:Link\r\n inet6 addr: 2030:30:30:30::10/64 Scope:Link\r\n UP BROADCAST MULTICAST MTU:9000 Metric:1\r\n RX packets:0 errors:0 dropped:0 overruns:0 frame:0\r\n TX packets:62 errors:0 dropped:0 overruns:0 carrier:0\r\n collisions:0 txqueuelen:0 \r\n RX bytes:0 (0.0 b) TX bytes:7004 (6.8 KiB)\r\n\r\n'
pattern = '(eth6\.36\s+Link encap:Ethernet\s*HWaddr\s*\w\w:\w\w:.+\s*inet addr:36.36.36.10\s*Bcast:36.36.36.255\s*Mask:255.255.255.0\s*\inet6 addr:\s*\w\w\w\w:.+)'
match = re.search(pattern, out)
print match.groups()
输出:
('eth6.36 Link encap:Ethernet HWaddr A0:36:9F:5F:24:EE \r\n inet addr:36.36.36.10 Bcast:36.36.36.255 Mask:255.255.255.0\r\n inet6 addr: fe80::a236:9fff:fe5f:24ed/64 Scope:Link\r',)
答案 0 :(得分:2)
您可以根据需要移动括号。 喜欢
pattern = '(eth6\.36\s+Link encap:Ethernet\s*HWaddr\s*\w\w:\w\w:.+\s*inet addr:36.36.36.10\s*Bcast:36.36.36.255\s*Mask:255.255.255.0\s*\inet6 addr:\s*\w\w\w\w:.+) Scope:Link'
将获得
In [9]: match.groups()[0]
Out[9]: 'eth6.36 Link encap:Ethernet HWaddr A0:36:9F:5F:24:EE \r\n inet addr:36.36.36.10 Bcast:36.36.36.255 Mask:255.255.255.0\r\n inet6 addr: fe80::a236:9fff:fe5f:24ed/64'
和
pattern = 'eth6\.36\s+Link encap:Ethernet\s*HWaddr\s*\w\w:\w\w:.+\s*inet addr:36.36.36.10\s*Bcast:36.36.36.255\s*Mask:255.255.255.0\s*\inet6 addr:\s*(\w\w\w\w:.+) Scope:Link'
将获得
In [16]: match.groups()[0]
Out[16]: 'fe80::a236:9fff:fe5f:24ed/64'
答案 1 :(得分:0)
由于您正在处理ifconfig
的(标准化)输出,为什么不完全消除 regex ,只是操纵字符串?
$ cat /tmp/tmp.py
#!/usr/bin/env python3
out ='ifconfig eth6.36\r\neth6.36 Link encap:Ethernet HWaddr A0:36:9F:5F:24:EE \r\n inet addr:36.36.36.10 Bcast:36.36.36.255 Mask:255.255.255.0\r\n inet6 addr: fe80::a236:9fff:fe5f:24ed/64 Scope:Link\r\n inet6 addr: 2030:30:30:30::10/64 Scope:Link\r\n UP BROADCAST MULTICAST MTU:9000 Metric:1\r\n RX packets:0 errors:0 dropped:0 overruns:0 frame:0\r\n TX packets:62 errors:0 dropped:0 overruns:0 carrier:0\r\n collisions:0 txqueuelen:0 \r\n RX bytes:0 (0.0 b) TX bytes:7004 (6.8 KiB)\r\n\r\n'
ip6 = out.split()[6]
print(ip6)
给你:
$ python /tmp/tmp.py
A0:36:9F:5F:24:EE