判断一个字符串是否是合法IP地址

时间:2020-01-08
本文章向大家介绍判断一个字符串是否是合法IP地址,主要包括判断一个字符串是否是合法IP地址使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
 1 # -*- coding: utf-8 -*-
 2 """
 3 @File:test06_判断ip地址是否合法.py    
 4 @E-mail:364942727@qq.com
 5 @Time:2020-01-08 14:06 
 6 @Author:Nobita   
 7 @Version:1.0   
 8 @Desciption:判断一个字符串是否是合法IP地址
 9 """
10 
11 import re
12 
13 '''
14 题目:判断一个字符串是否是合法IP地址。
15 '''
16 
17 
18 class Solution:
19     # write code here.
20     def judge_ip_address_one(self, ip_str):
21         '''方法一:正则匹配的方法'''
22         compile_ip = re.compile('^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$')
23         if compile_ip.match(ip_str):
24             return True
25         else:
26             return False
27 
28     def judge_ip_address_two(self, ip_str):
29         '''方法二:字符串的方法'''
30         if '.' not in ip_str:
31             return False
32         elif ip_str.count('.') != 3:
33             return False
34         else:
35             flag = True
36             ip_list = ip_str.split('.')
37             for i in ip_list:
38                 try:
39                     ip_num = int(i)
40                     if ip_num >= 0 and ip_num <= 255:
41                         pass
42                     else:
43                         flag = False
44                 except:
45                     flag = False
46             return flag
47 
48 
49 if __name__ == '__main__':
50     ip_list = ['', '172.31.137.251', '100.10.0.1000', '1.1.1.1', '12.23.13', 'aa.12.1.2', '12345678', '289043jdhjkbh']
51     for ip in ip_list:
52         # if Solution().judge_ip_address_one(ip):  # 正则匹配的方法
53         if Solution().judge_ip_address_two(ip):  # 字符串的方法
54             print('{}是合法的ip地址!'.format(ip))
55         else:
56             print('{}是不合法的ip地址!'.format(ip))

原文地址:https://www.cnblogs.com/chenshengkai/p/12166630.html