Python实现随机生成手机号及正则验证手机号的方法
作者:tian_shl 时间:2021-05-30 01:41:27
本文实例讲述了Python实现随机生成手机号及正则验证手机号的方法。分享给大家供大家参考,具体如下:
依据
根据2017年10月份最新的手机号正则进行编码, 正则如下:(13\d|14[579]|15[^4\D]|17[^49\D]|18\d)\d{8}
代码
# -*- coding: utf-8 -*-
import random
def create_phone():
# 第二位数字
second = [3, 4, 5, 7, 8][random.randint(0, 4)]
# 第三位数字
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]
# 最后八位数字
suffix = random.randint(9999999,100000000)
# 拼接手机号
return "1{}{}{}".format(second, third, suffix)
# 生成手机号
phone = create_phone()
print(phone)
运行结果
13937342780
15835720604
14589505530
...
PS:这里再为打击推荐一款功能相似的在线工具供大家参考:
在线随机生成个人信息数据工具:
http://tools.jb51.net/aideddesign/rnd_userinfo
验证 (使用正则验证)
# -*- coding: utf-8 -*-
import random
import re
def create_phone():
# 第二位数字
second = [3, 4, 5, 7, 8][random.randint(0, 4)]
# 第三位数字
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]
# 最后八位数字
suffix = random.randint(9999999,100000000)
# 拼接手机号
return "1{}{}{}".format(second, third, suffix)
# 生成手机号
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!")
验证结果
18662182464
Test passed!15896505277
Test passed!14952715286
Test passed!...
PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:
JavaScript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript
正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg
希望本文所述对大家Python程序设计有所帮助。
来源:https://blog.csdn.net/xiaobuding007/article/details/78726833
标签:Python,随机生成,正则验证,手机号
0
投稿
猜你喜欢
基于Python把网站域名解析成ip地址
2021-08-23 05:31:06
实操MySQL+PostgreSQL批量插入更新insertOrUpdate
2024-01-17 09:06:19
PyQt5 多窗口连接实例
2021-06-17 01:32:09
python学习Selenium介绍及安装部署详解
2021-02-09 21:56:58
深度学习Tensorflow2.8实现GRU文本生成任务详解
2022-07-27 09:04:21
python中的线程threading.Thread()使用详解
2021-02-25 21:38:38
python实现图像处理之PiL依赖库的案例应用详解
2023-04-06 09:08:04
js substr支持中文截取函数代码(中文是双字节)
2024-04-10 10:44:58
浅谈MySql update会锁定哪些范围的数据
2024-01-26 21:40:34
SQL语句 一个简单的字符串分割函数
2011-10-24 20:06:33
Python线程指南分享
2023-01-13 15:33:58
一场关于YUI3/jQuery的精彩辩论
2010-11-11 12:50:00
详细讲解Python中的文件I/O操作
2022-01-01 19:04:53
实例讲解启动mysql server失败的解决方法
2008-12-26 17:27:00
探讨php中防止SQL注入最好的方法是什么
2023-09-11 14:20:48
合并SQL脚本文件的方法分享
2024-01-21 10:00:49
JS模拟实现哈希表及应用详解
2024-04-23 09:25:52
python自动化实现登录获取图片验证码功能
2022-09-21 13:23:59
jQuery+php简单实现全选删除的方法
2023-11-05 20:23:38
django框架F&Q 聚合与分组操作示例
2021-05-21 02:13:56