2013-07-16 64 views
1

我想使用Python正則表達式匹配IP範圍。Python正則表達式匹配IP範圍

For Ex。作爲跟隨谷歌機器人IP範圍

66.249.64.0 - 66.249.95.255

re.compile(r"66.249.\d{1,3}\.\d{1,3}$") 

我無法弄清楚如何做到這一點?我發現使用Java完成了一個this

+0

您是否想l在更大的文本中找到一個IP地址,還是隻有一個包含IP地址的字符串? –

+0

@Joel Cornett:我有一個帶有IP地址的文本文件,我想從它過濾掉一些IP地址 –

+0

注意:如果你在網絡地址上做了很多工作,你可能想檢查一下[netaddr package ](https://pypi.python.org/pypi/netaddr)。 – torek

回答

1

您可以使用此:

(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) 

說明:

re.compile(r"66\.249\.(?:6[4-9]|[78]\d|9[0-5])\.\d{1,3}$") 

,如果你的動機,你可以通過更換\d{1,3}

一個正則表達式引擎不知道什麼是數字範圍是。描述範圍的唯一方法是寫一切準備用交替:

6[4-9] | [78][0-9] | 9[0-5] 

6   can be followed by 4 to 9 --> 64 to 69 
7 or 8  can be followed by 0 to 9 --> 70 to 89 
9   can be followed by 0 to 5 --> 90 to 95 
+0

Excellant .. :)工作很好,非常感謝! –

+0

還有一件事,你能解釋一下嗎? –

0

最後一個數字是:

[01]?\d{1,2}|2[0-4]\d|25[0-5] 

的第三個數字是:

6[4-9])|[78]\d|9[0-5] 
1

使用socket.inet_aton

import socket 
ip_min, ip_max = socket.inet_aton('66.249.64.0'), socket.inet_aton('66.249.95.255') 

if ip_min <= socket.inet_aton('66.249.63.0') <= ip_max: 
    #do stuff here 
相關問題