2015-10-17 29 views
0

我好苦於從字符串中提取IPv4地址。Python正則表達式來識別來自字符串的IPv4地址


我的輸入字符串&約束如下:

  • IPv4的範圍:0.0.0.0255.255.255.255
  • IPv4地址可以/可以不存在字符串
    • 有效實例中: this is an ip & this is an ip 200.100.2.32
  • 字符串可以與IPv4地址
    • 有效的例子開始:200.100.2.32 is an ip |輸出:['200.100.2.32']
    • 無效示例:200.100.2.32is an ip |輸出:[]
  • 字符串可以與IPv4地址
    • 有效的例子結束:the ip is 200.100.2.32 |輸出:['200.100.2.32']
    • 無效示例:the ip is200.100.2.32 |輸出:[]
  • 字符串可能包含在中間的IPv4地址,如果確實如此 - 將有一個空間之前和IPv4地址之後。
    • 有效範例:the ip is 200.100.2.32 and it is ipv4 |輸出:['200.100.2.32']
    • 有效範例:the ip is 200.100.2.32and it is ipv4 |輸出:[]
  • 多個IP可存在於單個字符串
    • 有效實例:200.100.2.32 100.50.1.16 |輸出:['200.100.2.32', '100.50.1.16']
    • 無效示例:200.100.2.32.100.50.1.16 |輸出:[]

我試圖建立上述情況一個正則表達式,它們看起來相當簡單,我不能夠將所有的正則表達式檢查。

我已經提到的回答這些鏈接:Link1Link2Link3


有人可以幫助我在正確的方向?總結:

  • 的IPv4將有一個空間之前或字符串
  • 的IPv4的開頭開始後,將有一個空間或字符串
  • 的IPv4月底結束服從範圍: 0.0.0.0255.255.255.255

代碼

def find_ip(str) : 
    ip_pattern = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s') # need to strengthen the regex here 
    ip = re.findall(ip_pattern, str) 
    return ip 
+0

你寫了什麼代碼? –

+0

在一分鐘內添加代碼。進行編輯。 – sudhishkr

+0

['ipaddress'](https://docs.python.org/3/library/ipaddress.html)模塊可以幫助你嗎? 'split'字符串和'try'分別從每個字符串調用['IPv4Adress'](https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Address)。 – Navith

回答

1

正則表達式:

(?:^|\b(?<!\.))(?:1?\d\d?|2[0-4]\d|25[0-5])(?:\.(?:1?\d\d?|2[0-4]\d|25[0-5])){3}(?=$|[^\w.]) 

比賽的example

相關問題