python笔试面试项目实战2020百练7使用正则表达式判断IP

2020-01-14  本文已影响0人  python测试开发

使用正则表达式判断IP是否合法

有socket等库的方法已经实现了IP合法性的检查,这个是某外企(flexport)的面试题,要求不能使用现成的库。

输入:比如1.2.3.4
输出: True or False

$ python check_ip.py 
check_ip('1.2.3.4') :  True
check_ip('1.2.3.444') :  False

https://github.com/china-testing/python-testing-examples/tree/master/interview

check_ip.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 技术支持:dwz.cn/qkEfX1u0 项目实战讨论QQ群630011153 144081101
# CreateDate: 2019-12-29

import re

def check_ip(address):
    if type(address) != str:
        return False
    expression = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
    if not expression.match(address):
        return False
    for number in address.split('.'):
        if number.startswith('0') and len(number) >1 :
            return False
        if int(number) < 0 or int(number) > 255:
            return False
    return True

if __name__ == '__main__':
    
    print("check_ip('1.2.3.4')", ": ", check_ip('1.2.3.4'))
    print("check_ip('1.2.3.444')", ": ", check_ip('1.2.3.444'))

参考资料

寻找字符串中可能的ip地址

输入:字符串,比如"134578'
输出: IP地址列表

$ python check_ip2.py 
123425 可能的ip有 ['1.234.2.25', '12.34.2.25', '123.4.2.25']

https://github.com/china-testing/python-testing-examples/tree/master/interview

check_ip2.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 技术支持:dwz.cn/qkEfX1u0 项目实战讨论QQ群630011153 144081101
# CreateDate: 2019-12-29

from check_ip import check_ip as check

def address(s, state=()):
    result = []
    length = len(s)
    start = 1 if not state else state[-1]
    for pos in range(start,length):
        if pos not in state:
            if len(state) == 2:
                seqs = state + (pos,)
                ip_str = f'{s[:seqs[0]]}.{s[seqs[0]:seqs[1]]}.{s[seqs[1]:seqs[2]]}.{s[seqs[1]:]}'
                if check(ip_str):
                    result.append(ip_str)
            else:
                result = result + address(s, state + (pos,))
    return result
               


if __name__ == '__main__':
    
    tmp = '123425'
    print(tmp, "可能的ip有", address(tmp))

业界常用判断ip方法1

https://github.com/china-testing/python-testing-examples/tree/master/interview

check_ip3.py

image.png

业界常用判断ip方法

https://github.com/china-testing/python-testing-examples/tree/master/interview

check_ip3.py

image.png

check_ip4.py

第三方库IPy也可以达到类似的效果。

上一篇下一篇

猜你喜欢

热点阅读