当我在if语句中使用多个`和`时没有得到输出

时间:2017-07-16 16:53:53

标签: python regex

下面是我在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

我无法找到我获得此输出的原因。

2 个答案:

答案 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(),以便比较数字