如何用Python验证IP地址和端口号字符串的合法性?
- 内容介绍
- 文章标签
- 相关推荐
本文共计275个文字,预计阅读时间需要2分钟。
IP地址合规性校验是开发中常用的重要环节,看似简单,作用显著,但编写时易出错。今天我们来总结一下,看看三种常用IP地址格式校验的方法。
IP合法性校验是开发中非常常用的,看起来很简单的判断,作用确很大,写起来比较容易出错,今天我们来总结一下,看一下3种常用的IP地址合法性校验的方法。
不使用正则表达式的方式:
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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。
本文共计275个文字,预计阅读时间需要2分钟。
IP地址合规性校验是开发中常用的重要环节,看似简单,作用显著,但编写时易出错。今天我们来总结一下,看看三种常用IP地址格式校验的方法。
IP合法性校验是开发中非常常用的,看起来很简单的判断,作用确很大,写起来比较容易出错,今天我们来总结一下,看一下3种常用的IP地址合法性校验的方法。
不使用正则表达式的方式:
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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

