随机生成电话号码,然后提取里面是电信,移动,联通,用正则表达式完成
时间: 2023-06-24 13:03:39 浏览: 364
Java读取文件及基于正则表达式的获取电话号码功能详解
生成随机电话号码的代码:
```python
import random
def generate_phone_number():
prefix = ["130", "131", "132", "133", "134", "135", "136", "137", "138", "139",
"150", "151", "152", "153", "155", "156", "157", "158", "159",
"170", "176", "177", "178",
"180", "181", "182", "183", "184", "185", "186", "187", "188", "189"]
return random.choice(prefix) + "".join(random.sample("0123456789", 8))
print(generate_phone_number())
```
接下来,我们可以使用正则表达式来判断手机号码属于哪个运营商。以下是正则表达式的实现:
```python
import re
phone_number = generate_phone_number()
# 判断是否为中国电信号码
if re.match(r"^133\d{8}$|153\d{8}$|173\d{8}$|177\d{8}$|180\d{8}$|181\d{8}$|189\d{8}$", phone_number):
print(f"{phone_number} 是中国电信号码")
# 判断是否为中国联通号码
elif re.match(r"^130\d{8}$|131\d{8}$|132\d{8}$|155\d{8}$|156\d{8}$|166\d{8}$|170\d{8}$|171\d{8}$|175\d{8}$|176\d{8}$|185\d{8}$|186\d{8}$", phone_number):
print(f"{phone_number} 是中国联通号码")
# 判断是否为中国移动号码
elif re.match(r"^134\d{8}$|135\d{8}$|136\d{8}$|137\d{8}$|138\d{8}$|139\d{8}$|147\d{8}$|148\d{8}$|150\d{8}$|151\d{8}$|152\d{8}$|157\d{8}$|158\d{8}$|159\d{8}$|165\d{8}$|172\d{8}$|178\d{8}$|182\d{8}$|183\d{8}$|184\d{8}$|187\d{8}$|188\d{8}$", phone_number):
print(f"{phone_number} 是中国移动号码")
# 其他号码
else:
print(f"{phone_number} 不属于电信、移动、联通之一")
```
注意,以上正则表达式只能识别中国大陆地区的手机号码。如果需要支持其他地区的手机号码,需要根据具体情况修改正则表达式。
阅读全文