Python檢測端口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]?dd?).){3}(25[0-5]|2[0-4]d|[01]?dd?)$’) 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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: