2013-05-03 27 views

回答

2

如果你正在尋找一個完整的正則表達式來獲得IPv4地址,你可以找到最合適的正則表達式here您可以使用正則表達式的IP d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}

text = "126.23.73.34"; 
match = re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', text) 
if match: 
    print "match.group(1) : ", match.group(0) 

來限制IP地址的所有4個數字0-255,你可以用這一個從上面的源採取:

(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) 
+0

這是正確的正則表達式IPv4地址btw:'\ b(25 [0-5] | 2 [0-4] [0-9] | [01]?[0-9] [0-9]?)\。(25 [0- 5] | 2 [0-4] [0-9] | [01] [0-9] [0-9])\(25 [0-5] | 2 [0-4] - [O- 9] | [01] [0-9] [0-9])\(25 [0-5] |?2 [0-4] [0-9] | [01] [0-9] [0-9]?)\ b' – tamasgal 2013-05-03 10:57:41

+0

是的。我不確定他是否在尋找知識產權,但我承擔了很多。我將包含一個鏈接作爲參考。 – eandersson 2013-05-03 10:58:24

+0

我不確定您的答案結果的格式是OP所需的,請參閱:C:\ wamp \ www> Example.py ('192','168','0','1') ('192','168','0','254') – o0rebelious0o 2013-05-03 11:31:50

0

您可以使用此。它只會接受VALID IP地址:

import re 
pattern = "\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b" 
text = "192.168.0.1 my other IP is 192.168.0.254 but this one isn't a real ip 555.555.555.555" 
m = re.findall(pattern, text) 
for i in m : 
    print(i) 

OUTPUT:

C:\wamp\www>Example.py 
192.168.0.1 
192.168.0.254 

--Tested和工作

+0

當然可行,但如果它不是一個有效的IP呢?例如555.168.0.1? – eandersson 2013-05-03 11:04:52

+0

現在的問題是,我引用「從文檔中獲取126.23.73.34等數字模式並將其提取出來」並沒有說明實際驗證提取的值 – o0rebelious0o 2013-05-03 11:08:09

+0

這並不意味着其他人不會看看這個問題一個月,或從現在開始。提供最完整的答案始終符合社區的最佳利益。 – eandersson 2013-05-03 11:14:49

1

如果,如果它是一個html文本;你可以使用HTML解析器(如BeautifulSoup)解析它,一個正則表達式來選擇一些字符串看起來像一個IP,並socket模塊驗證IPS:

import re 
import socket 
from bs4 import BeautifulSoup # pip install beautifulsoup4 

def isvalid(addr): 
    try: 
     socket.inet_aton(addr) 
    except socket.error: 
     return False 
    else: 
     return True 

soup = BeautifulSoup(webpage) 
ipre = re.compile(r"\b\d+(?:\.\d+){3}\b") # matches some ips and more 
ip_addresses = [ip for ips in map(ipre.findall, soup(text=ipre)) 
       for ip in ips if isvalid(ip)] 

注:只從文本如提取IPS ,它會忽略html屬性中的ips。

+0

BeautifulSoup是什麼? – Sazid 2013-05-04 10:20:43

+0

@Sazid:這是一個庫,您可以使用它從HTML文本中提取信息。我已添加鏈接到其文檔 – jfs 2013-05-04 12:52:11

+0

嘿,我已經安裝它,並表示感謝。我也有它的文檔! – Sazid 2013-05-04 14:28:32

相關問題