下面是我在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
我无法找到我获得此输出的原因。
答案 0 :(得分:5)
您将匹配的字符串与另一个字符串进行比较,比较是词典,这不是您想要的。
您应该将输出转换为int并与int:
进行比较Button
OTOH,如果在Python 3上,您可以考虑使用ipaddress
库:
if int(match.group(1)) <= 255 and ... :
print "yes IP matched"
else :
print "no have not matched"
答案 1 :(得分:4)
因为您要比较strings
,它将与第一个数字进行比较,例如:
print '4' <= '255'
将输出
False
您需要将每个操作数输入到int()
,以便比较数字