python 用正则表达式的方法实现判断手机号所属运营商
时间: 2023-06-12 11:05:30 浏览: 57
可以通过正则表达式匹配手机号码前三位来判断手机号所属的运营商,具体实现步骤如下:
1. 定义三个正则表达式,分别匹配中国移动、中国联通、中国电信的手机号码前三位。
```
import re
cm_regex = re.compile(r'^1(3[4-9]|4[7]|5[012789]|7[28]|8[23478])')
cu_regex = re.compile(r'^1(3[0-2]|4[5]|5[56]|6[6]|7[0156]|8[56])')
ct_regex = re.compile(r'^1(33|49|53|7[37]|8[019])')
```
2. 编写函数 `get_operator(phone_num)`,实现根据手机号码匹配运营商的功能。
```
def get_operator(phone_num):
if cm_regex.match(phone_num):
return '中国移动'
elif cu_regex.match(phone_num):
return '中国联通'
elif ct_regex.match(phone_num):
return '中国电信'
else:
return '未知运营商'
```
3. 调用函数 `get_operator(phone_num)`,传入手机号码参数,即可返回该手机号码所属的运营商。
```
phone_num = '13812345678'
operator = get_operator(phone_num)
print(phone_num + ' 的运营商是:' + operator)
```
输出结果为:
```
13812345678 的运营商是:中国移动
```