使用正則表達(dá)式判斷IP是否合法
有socket等庫(kù)的方法已經(jīng)實(shí)現(xiàn)了IP合法性的檢查讳推,這個(gè)是某外企(flexport)的面試題惹悄,要求不能使用現(xiàn)成的庫(kù)。
輸入:比如1.2.3.4
輸出: True or False
- 執(zhí)行演示
$ 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 -*-
# 技術(shù)支持:dwz.cn/qkEfX1u0 項(xiàng)目實(shí)戰(zhàn)討論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'))
參考資料
- 本文最新版本地址
- 本文涉及的python測(cè)試開發(fā)庫(kù) 謝謝點(diǎn)贊季俩!
- 本文相關(guān)海量書籍下載
- python工具書籍下載-持續(xù)更新
- 本文配套視頻在線播放 下載
尋找字符串中可能的ip地址
輸入:字符串昼蛀,比如"134578'
輸出: IP地址列表
- 執(zhí)行演示
$ 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 -*-
# 技術(shù)支持:dwz.cn/qkEfX1u0 項(xiàng)目實(shí)戰(zhàn)討論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))
業(yè)界常用判斷ip方法1
https://github.com/china-testing/python-testing-examples/tree/master/interview
check_ip3.py
image.png
業(yè)界常用判斷ip方法
https://github.com/china-testing/python-testing-examples/tree/master/interview
check_ip3.py
image.png
check_ip4.py
第三方庫(kù)IPy也可以達(dá)到類似的效果。