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

Nit*_*esh 1 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"
Run Code Online (Sandbox Code Playgroud)

我低于输出

no have not matched
Run Code Online (Sandbox Code Playgroud)

我无法找到为什么我得到这个输出.

Mos*_*oye 5

您将匹配的字符串与另一个字符串进行比较,比较是词典编纂,这不是您想要的.

您应该将输出转换为int并与int进行比较:

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

OTOH,如果在Python 3上,您可以考虑使用该ipaddress库:

import ipaddress

try:
   ipaddress.IPv4Address(addr)
   print("yes IP matched")
except ipaddress.AddressValueError:
   print("no have not matched")
Run Code Online (Sandbox Code Playgroud)