python正则表达式解析不同语言环境的ifconfig输出

时间:2015-04-20 11:34:11

标签: python regex locale ifconfig

我正在寻找从ifocnfig输出解析IP和子网详细信息的最佳方法。

我不想基于inet addrMask:来搜索它,因为当应用不同的区域设置时,正则表达式会在更改字符串时失败。

以下是示例文字:

eth0      Link encap:Ethernet  HWaddr 00:18:F3:BE:18:1E
          inet addr:192.168.10.15  Bcast:192.168.10.255  Mask:255.255.255.0
          inet6 addr: fe80::218:f3ff:febe:181e/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:39456 errors:0 dropped:0 overruns:0 frame:0
          TX packets:45730 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:25457904 (24.2 Mb)  TX bytes:6540945 (6.2 Mb)
          Interrupt:20

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:182 errors:0 dropped:0 overruns:0 frame:0
          TX packets:182 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:12812 (12.5 Kb)  TX bytes:12812 (12.5 Kb)

我尝试了几种方法,例如:使用\d+\.\d+\.\d+\.\d+,但找不到最好的方法。需要帮助。

2 个答案:

答案 0 :(得分:0)

import re
tempstr='blah blah 172.16.13.35 blah blah 23.85.85.94'

matches = re.findall(r'\d+[.]\d+[.]\d+[.]\d+', tempstr) 
for match in matches:
    print match

此代码将打印在给定字符串tempstr中找到的所有ip。 程序的输出是 的 172.16.13.35 23.85.85.94

答案 1 :(得分:0)

我可以建议使用这个正则表达式:

\b\d+(?:\.\d+){3}\b

它应与Multiline选项一起使用。

请参阅demo

结果在第1组内。见sample code

import re
p = re.compile(ur'\b\d+(?:\.\d+){3}\b', re.MULTILINE)
test_str = u"eth0      Link encap:Ethernet  HWaddr 00:18:F3:BE:18:1E\n          inet addr:192.168.10.15  Bcast:192.168.10.255  Mask:255.255.255.0\n          inet6 addr: fe80::218:f3ff:febe:181e/64 Scope:Link\n          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1\n          RX packets:39456 errors:0 dropped:0 overruns:0 frame:0\n          TX packets:45730 errors:0 dropped:0 overruns:0 carrier:0\n          collisions:0 txqueuelen:1000\n          RX bytes:25457904 (24.2 Mb)  TX bytes:6540945 (6.2 Mb)\n          Interrupt:20\n\nlo        Link encap:Local Loopback\n          inet addr:127.0.0.1  Mask:255.0.0.0\n          inet6 addr: ::1/128 Scope:Host\n          UP LOOPBACK RUNNING  MTU:16436  Metric:1\n          RX packets:182 errors:0 dropped:0 overruns:0 frame:0\n          TX packets:182 errors:0 dropped:0 overruns:0 carrier:0\n          collisions:0 txqueuelen:0\n          RX bytes:12812 (12.5 Kb)  TX bytes:12812 (12.5 Kb)"
print re.findall(p, test_str)

输出:

 [u'192.168.10.15', u'192.168.10.255', u'255.255.255.0', u'127.0.0.1', u'255.0.0.0']