本文實(shí)例講述了Python實(shí)現(xiàn)隨機(jī)生成手機(jī)號(hào)及正則驗(yàn)證手機(jī)號(hào)的方法。分享給大家供大家參考,具體如下:
依據(jù)
根據(jù)2017年10月份最新的手機(jī)號(hào)正則進(jìn)行編碼, 正則如下:
(13/d|14[579]|15[^4/D]|17[^49/D]|18/d)/d{8}
代碼
# -*- coding: utf-8 -*-import randomdef create_phone(): # 第二位數(shù)字 second = [3, 4, 5, 7, 8][random.randint(0, 4)] # 第三位數(shù)字 third = { 3: random.randint(0, 9), 4: [5, 7, 9][random.randint(0, 2)], 5: [i for i in range(10) if i != 4][random.randint(0, 8)], 7: [i for i in range(10) if i not in [4, 9]][random.randint(0, 7)], 8: random.randint(0, 9), }[second] # 最后八位數(shù)字 suffix = random.randint(9999999,100000000) # 拼接手機(jī)號(hào) return "1{}{}{}".format(second, third, suffix)# 生成手機(jī)號(hào)phone = create_phone()print(phone)運(yùn)行結(jié)果
13937342780
15835720604
14589505530
...
驗(yàn)證 (使用正則驗(yàn)證)
# -*- coding: utf-8 -*-import randomimport redef create_phone(): # 第二位數(shù)字 second = [3, 4, 5, 7, 8][random.randint(0, 4)] # 第三位數(shù)字 third = { 3: random.randint(0, 9), 4: [5, 7, 9][random.randint(0, 2)], 5: [i for i in range(10) if i != 4][random.randint(0, 8)], 7: [i for i in range(10) if i not in [4, 9]][random.randint(0, 7)], 8: random.randint(0, 9), }[second] # 最后八位數(shù)字 suffix = random.randint(9999999,100000000) # 拼接手機(jī)號(hào) return "1{}{}{}".format(second, third, suffix)# 生成手機(jī)號(hào)phone = create_phone()print(phone)# 正則reg = re.compile("(13/d|14[579]|15[^4/D]|17[^49/D]|18/d)/d{8}")print("Test passed!" if reg.match(phone) else "Test failed!")驗(yàn)證結(jié)果
18662182464
Test passed!15896505277
Test passed!14952715286
Test passed!...
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選