一个刚结束的笔试题目,简单贴一下吧,下面是具体实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
#!usr/bin/env python
#encoding:utf-8
'''
__Author__:沂水寒城
'''
import re
def judge_legal_ip(one_str):
'''
正则匹配方法
判断一个字符串是否是合法IP地址
'''
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?)$' )
if compile_ip.match(one_str):
return True
else :
return False
def judge_legal_ip2(one_str):
'''
简单的字符串判断
'''
if '.' not in one_str:
return False
elif one_str.count( '.' )! = 3 :
return False
else :
flag = True
one_list = one_str.split( '.' )
for one in one_list:
try :
one_num = int (one)
if one_num> = 0 and one_num< = 255 :
pass
else :
flag = False
except :
flag = False
return flag
if __name__ = = '__main__' :
ip_list = [' ',' 172.31 . 137.251 ',' 100.10 . 0.1000 ',' 1.1 . 1.1 ',' 12.23 . 13 ',' aa. 12.1 . 2 ',' 12345678 ',' 289043jdhjkbh ']
for one_str in ip_list:
if judge_legal_ip(one_str): #正则方法
#if judge_legal_ip2(one_str): #字符串方法
print '{0} is a legal ip address!' . format (one_str)
else :
print '{0} is not a legal ip address!' . format (one_str)
|
结果如下:
1
2
3
4
5
6
7
8
|
is not a legal ip address!
172.31 . 137.251 is a legal ip address!
100.10 . 0.1000 is not a legal ip address!
1.1 . 1.1 is a legal ip address!
12.23 . 13 is not a legal ip address!
aa. 12.1 . 2 is not a legal ip address!
12345678 is not a legal ip address!
289043jdhjkbh is not a legal ip address!
|
以上这篇python实现判断一个字符串是否是合法IP地址的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/together_cz/article/details/77533082