实战:格式校验

40.11 实战:格式校验

用 fullmatch 验证整串:手机号、邮箱、身份证号(简化版)等。

校验前先 strip() 去首尾空格。

校验函数

# ========================================
# 示例:手机号与邮箱校验
# 说明:fullmatch 整串匹配;简化规则仅供学习
# ========================================
import re

def is_phone(s):
    return re.fullmatch(r'1[3-9]\d{9}', s.strip()) is not None

def is_email(s):
    return re.fullmatch(r'[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}', s.strip()) is not None

print(is_phone('13812345678'))   # True
print(is_email('user@mail.com')) # True
print(is_phone('12345'))         # False

⚠️ 常见错误与正确对比

❌ 错误写法
re.search(pat, s) 做完整校验
✅ 正确写法
re.fullmatch(pat, s.strip())

📌 search 只要求部分匹配,\"abc13812345678\" 也会通过。