1、需求:输入字符串,如果是IP地址,输出True,如果不是,则输出False。定义一个函数,及编写测试这个函数的测试用例。
2、思路:先确认IP的格式:(0~255).(0~255).(0~255).(0~255)
3、编码如下:
import re def judge_legal_ip(input): p = re.compile('^((25[0-5]|2[0-4]d|[01]?dd?).){3}(25[0-5]|2[0-4]d|[01]?dd?)$') if re.match(p,input): return True else: return False
if __name__ == '__main__': ip_list = ['0.0.0.0','35.255.12.12','255:255:255:255','255.255.255.256','','12345678','12.123123123','12.23.13', 'aa.12.1.2', '12.23.12.32.12','12...12'] for one_str in ip_list: if judge_legal_ip(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、正常最小值用例:0.0.0.0
2、正常用例第二个值首数字大于2:35.255.12.12
2、正常最大值用例:255:255:255:255
3、异常用例:255.255.255.256
4、异常用例:空字符串
5、异常用例:没有带.字符串
6、异常用例:仅带一个.
7、异常用例:仅带2个.
8、异常用例:带3个.,有字母
8、异常用例:带4个.
9、异常用例:带3个连续的点
正则表达式学习推荐:
https://www.cnblogs.com/chuxiuhong/p/5885073.html Python 正则表达式入门(初级篇)
http://www.cnblogs.com/chuxiuhong/p/5907484.html Python 正则表达式入门(中级篇)