IP的格式:(1-255).(0-255).(0-255).(0-255)
#_*_ coding:utf-8 _*_
import re
def ipJudeg(ip):
"""
2021/10/25
判断字符串是否符合ip地址规则
:param ip:
:return:
"""
if '.' not in ip :
return False
elif len(re.findall('\.',ip))!=3: #可直接count ip.count('.') 正则表达式中.匹配所有非\n的字符,所以'.'要使用转义
return False
else:
Ls=re.split('.',ip)
try:
if int(Ls[0]) in range(1,256) and int(Ls[1]) in range(0,256) and int(Ls[2]) in range(0,256) and int(Ls[3]) in range(0,256):
return True
else:
return False
except Exception as e:
return False
if __name__=='__main__':
ipL=['','134','1.3.4.5.6','1.2','....','ad.1.2.3','\.\.\.\.','0.25.25.25','1.256.1.1','12.12.12.12']
for L in ipL:
if ipJudeg(L):
print('"%s" is ip'%L)
else:
print('"%s" isn\'t ip'%L)