下面是我在python中匹配IP的简单代码
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
我无法找到为什么我得到这个输出。
请您参考如下方法:
您正在将匹配的字符串与另一个字符串进行比较,比较是字典顺序,这不是您想要的。
您应该将输出转换为 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")
