import re
# ^(\+86)? 表示+86为可选
# 1[356789] 表示中国的手机号为13、15、16、17、18、19开头
# \d{9} 表示9位数字,因为前面已经有13、15、16、17、18或19了,所以这里是9
# (\d{3,4}-)? 表示区号,也是可选的
# \d{7,8} 表示7至8位座机号码
# 正则表达式可以使用括号进行分组,一对括号为一组
def identify_and_clean_phone_number(input_string):
# 判断是否为中国手机号
mobile_pattern = re.compile(r'^(\+86)?1[356789]\d{9}$')
# 判断是否为中国座机号(假设区号3-4位,电话号码7-8位)
landline_pattern = re.compile(r'^(\+86)?(\d{3,4}-)?\d{7,8}$')
mo = mobile_pattern.match(input_string)
if mo:
# 获取匹配到的字符串,去掉前缀 "+86"
matched_string = mo.group()[3:] if mo.group(1) else mo.group()
return "中国手机号码", matched_string
mo = landline_pattern.match(input_string)
if mo:
# 获取匹配到的字符串,去掉前缀 "+86"
matched_string = mo.group()[3:] if mo.group(1) else mo.group()
return "中国座机号码", matched_string
return "未知类型", input_string
# 示例用法
phone_number1 = "+8613345678901"
phone_number2 = "021-12345678"
result1_type, result1_matched = identify_and_clean_phone_number(phone_number1)
result2_type, result2_matched = identify_and_clean_phone_number(phone_number2)
print(f"{phone_number1} 是 {result1_type},匹配的字符串是 {result1_matched}")
print(f"{phone_number2} 是 {result2_type},匹配的字符串是 {result2_matched}")
Python使用正则表达式判断一串数字是否位中国手机号或座机号
于 2024-01-31 22:34:23 首次发布