chenshengkai
 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))

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-12-26
  • 2021-12-26
  • 2021-12-26
  • 2022-12-23
  • 2021-12-26
  • 2021-12-26
  • 2021-12-26
猜你喜欢
  • 2021-10-01
  • 2022-12-23
  • 2021-08-19
  • 2022-12-23
  • 2021-12-26
  • 2021-06-06
  • 2022-12-23
相关资源
相似解决方案