使用 re 库匹配 IP 地址
一, 说明
ip 地址为 xxx.xxx.xxx.xxx, 其中 xxx 为 0-255 直接数字.
本文匹配为 (1-255).(0-255).(0-255).(1-254)
二, 匹配表达式
1 ip_match = r"^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[1-9])\.)(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){2}(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[1-9])$"
三, 代码与自测
- # 自测情况
- def seperate_ip(ip_address):
- ip_match = r"^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[1-9])\.)(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){2}(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[1-9])$"
- if re.match(ip_match, ip_address):
- print ip_address+':', re.match(ip_match, ip_address)
- else:
- print ip_address+':', re.match(ip_match, ip_address)
- seperate_ip('1.108.116.1')
- seperate_ip('200.108.116.1')
- seperate_ip('100.108.116.1')
- seperate_ip('1.100.001.1')
- seperate_ip('001.100.001.001')
- seperate_ip('1.0.0.1')
- seperate_ip('100.255.255.1')
- seperate_ip('255.108.116.255')
- seperate_ip('1.100.001.000')
- seperate_ip('0.100.001.000')
- seperate_ip('0.108.116.1')
- seperate_ip('119.108.116.0')
- seperate_ip('000.108.116.1')
- seperate_ip('100.256.116.1')
- seperate_ip('100.100.256.1')
来源: http://www.bubuko.com/infodetail-3322904.html