python 正则RE匹配IP地址

使用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]|0?[1-9]0)\.)(?:(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]|0?[1-9]0)$"

 

三、代码与自测

 1 #自测情况
 2 def seperate_ip(ip_address):
 3     r"^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[1-9]|0?[1-9]0)\.)(?:(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]|0?[1-9]0)$"
 4     
 5     if re.match(ip_match, ip_address):
 6         print ip_address+':      ', re.match(ip_match, ip_address)
 7     else:
 8         print ip_address+':  ', re.match(ip_match, ip_address)
 9     
10 
11 seperate_ip('1.108.116.1')
12 seperate_ip('200.108.116.1')
13 seperate_ip('100.108.116.1')
14 seperate_ip('1.100.001.1')
15 seperate_ip('001.100.001.001')
16 seperate_ip('1.0.0.1')
17 seperate_ip('100.255.255.1')
18 
19 seperate_ip('255.108.116.255')
20 seperate_ip('1.100.001.000')
21 seperate_ip('0.100.001.000')
22 seperate_ip('0.108.116.1')
23 seperate_ip('119.108.116.0')
24 seperate_ip('000.108.116.1')
25 seperate_ip('100.256.116.1')
26 seperate_ip('100.100.256.1')

 

 

 

posted @ 2019-12-08 22:15  PerilongGideon  阅读(2195)  评论(0编辑  收藏  举报