2017-07-16 56 views
1

下面是我在Python匹配IP沒有得到輸出`和`在if語句

import os 
import sys 
import re 
str = "192.168.4.2" 
match = re.search("(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})", str) 
if ( match.group(1) <= "255" and match.group(2) <= "255" and 
     match.group(3) <= "255" and match.group(4) <= "255") : 
    print "yes IP matched" 
else : 
    print "no have not matched" 

我得到以下輸出簡單的代碼

no have not matched 

我不能找出爲什麼我得到這個輸出。

+0

我不是100%肯定,但我認爲你必須去除蜱(「)每一個操作數轉換爲int()各地你的255 – Thomas

+0

@ThomasMey,匹配的子字符串是* strings *。 「192」<255「並不比」192「<255」更正確。 –

+0

@CharlesDuffy是的,正如摩西所指出的那樣,他也必須將match.group包裝在一個int(..)中,以便比較起作用。 – Thomas

回答

4

因爲你是比較strings將由第一個數字比較,例如:

print '4' <= '255' 

將輸出

False 

需要鍵入以比較數字

5

你正在比較匹配的字符串與另一個字符串,比較是lexicographical,這不是你想要的。

你應該投的輸出爲int與一個int比較:

if int(match.group(1)) <= 255 and ... : 
    print "yes IP matched" 
else : 
    print "no have not matched" 

OTOH,如果在Python 3中,您可以考慮使用ipaddress庫:

import ipaddress 

try: 
    ipaddress.IPv4Address(addr) 
    print("yes IP matched") 
except ipaddress.AddressValueError: 
    print("no have not matched") 
+0

在Python中有一個'ipaddress'的反向鏈接:[py2-ipaddress](https://pypi.python.org/的PyPI/PY2-IPADDRESS)。 –