码迷,mamicode.com
首页 > 编程语言 > 详细

python端口IP字符串是否合法

时间:2020-06-02 16:10:02      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:表达   com   match   spl   python   mat   port   pytho   else   

不使用正则表达式的方式:

def is_ip(ip: str) -> bool:
    return True if [True] * 4 == [x.isdigit() and 0 <= int(x) <= 255 for x in ip.split(".")] else False

 使用正则表达式的方式

import re

def isIP(str):
    p = re.compile(‘^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$‘)
    if p.match(str):
        return True
    else:
        return False

  

另一种

def checkip(hostip):
    pat = re.compile(r‘([0-9]{1,3})\.‘)
    r = re.findall(pat,hostip+".")
    if len(r)==4 and len([x for x in r if int(x)>=0 and int(x)<=255])==4:
        return True
    else:
       return False

  

python端口IP字符串是否合法

标签:表达   com   match   spl   python   mat   port   pytho   else   

原文地址:https://www.cnblogs.com/hchan/p/13031788.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!