Python 正则表达式:10 个常用场景及示例
·
Python 正则表达式:10 个常用场景及示例
1. 验证手机号码
匹配中国大陆 11 位手机号:
import re
pattern = r'^1[3-9]\d{9}$'
phone = "13800138000"
print(bool(re.match(pattern, phone))) # 输出: True
2. 提取邮箱地址
从文本中提取邮箱:
text = "联系邮箱:contact@example.com 或 support@domain.org"
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)
print(emails) # 输出: ['contact@example.com', 'support@domain.org']
3. 匹配日期格式
识别 YYYY-MM-DD 格式日期:
date_str = "2023-10-01"
match = re.search(r'(\d{4})-(\d{2})-(\d{2})', date_str)
if match:
print(f"年: {match.group(1)}, 月: {match.group(2)}, 日: {match.group(3)}")
4. 密码强度验证
要求含大小写字母、数字、特殊字符且长度 8-20 位:
password = "P@ssw0rd!"
pattern = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,20}$'
print(bool(re.match(pattern, password))) # 输出: True
5. 提取超链接
从 HTML 中提取 URL:
html = '<a href="https://example.com">链接</a>'
urls = re.findall(r'href="(https?://[^"]+)"', html)
print(urls) # 输出: ['https://example.com']
6. 替换敏感词
将指定词汇替换为星号:
text = "禁止使用脏话或攻击性语言"
clean_text = re.sub(r'(脏话|攻击性)', '***', text)
print(clean_text) # 输出: "禁止使用***或***语言"
7. 分割字符串
按多字符分隔符切分字符串:
data = "苹果|香蕉,橙子;西瓜"
items = re.split(r'[|,;]', data)
print(items) # 输出: ['苹果', '香蕉', '橙子', '西瓜']
8. 匹配中文文本
提取纯中文字符段:
text = "Hello! 你好,今天是2023年。"
chinese_only = re.findall(r'[\u4e00-\u9fa5]+', text)
print(chinese_only) # 输出: ['你好', '今天是', '年']
9. 验证身份证号
匹配 18 位身份证号(简易版):
id_card = "11010519991231003X"
pattern = r'^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dX]$'
print(bool(re.match(pattern, id_card))) # 输出: True
10. 提取数字
从混合文本中提取所有数字:
text = "订单号: 2023A001, 金额: ¥128.50"
numbers = re.findall(r'\d+\.?\d*', text)
print(numbers) # 输出: ['2023', '001', '128.50']
关键函数说明
re.match(): 从字符串开头匹配re.search(): 扫描整个字符串返回首个匹配re.findall(): 返回所有匹配结果的列表re.sub(): 替换匹配内容re.split(): 按正则分割字符串
注:复杂场景建议使用
re.compile()预编译正则表达式提升性能,例如pattern = re.compile(r'...')。
更多推荐
所有评论(0)