一、正则表达式匹配练习
题目: 使用正则完成下列内容的匹配:
- 匹配陕西省区号 029-12345
- 匹配邮政编码 745100
- 匹配邮箱 [email protected]
- 匹配身份证号 62282519960504337X
代码:
import re
# 1. 匹配陕西省区号 029-12345
pattern_area = r'^029-\d{5}$' # 精确匹配 029- 开头,后接 5 位数字
test_area = '029-12345'
print("区号匹配:", re.match(pattern_area, test_area) is not None)
# 2. 匹配邮政编码 745100
pattern_post = r'^\d{6}$' # 精确匹配 6 位数字
test_post = '745100'
print("邮编匹配:", re.match(pattern_post, test_post) is not None)
# 3. 匹配邮箱 [email protected]
pattern_email = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
test_email = '[email protected]'
print("邮箱匹配:", re.match(pattern_email, test_email) is not None)
# 4. 匹配身份证号 62282519960504337X
pattern_id = r'^\d{17}[\dXx]$' # 17 位数字 + 1 位数字或 X/x
test_id = '62282519960504337X'
print("身份证匹配:", re.match(pattern_id, test_id) is not )





