正则表达式
正则表达式是一种强大的文本匹配工具,Python 通过 re 模块提供支持。
基本匹配
import re
# 匹配字符串
text = "Hello, Python 3.10!"
# 查找第一个匹配
match = re.search(r'Python', text)
if match:
print(f"找到匹配: {match.group()}") # Python
# 查找所有匹配
matches = re.findall(r'\d+', text)
print(f"所有数字: {matches}") # ['3', '10']
# 替换
new_text = re.sub(r'Python', 'Java', text)
print(f"替换后: {new_text}") # Hello, Java 3.10!
# 分割
parts = re.split(r'[,\s]+', text)
print(f"分割结果: {parts}") # ['Hello', 'Python', '3.10!']
常用模式
import re
# 匹配邮箱
email = "user@example.com"
pattern = r'[\w\.-]+@[\w\.-]+\.\w+'
if re.match(pattern, email):
print("有效的邮箱地址")
# 匹配手机号
phone = "13812345678"
pattern = r'1[3-9]\d{9}'
if re.match(pattern, phone):
print("有效的手机号")
# 匹配 URL
url = "https://www.example.com/path"
pattern = r'https?://[\w\.-]+/\S*'
if re.match(pattern, url):
print("有效的 URL")
# 匹配日期
date = "2026-01-25"
pattern = r'\d{4}-\d{2}-\d{2}'
if re.match(pattern, date):
print("有效的日期格式")
分组和捕获
import re
# 分组匹配
text = "张三: 25岁, 李四: 30岁"
pattern = r'(\w+): (\d+)岁'
matches = re.findall(pattern, text)
print(matches) # [('张三', '25'), ('李四', '30')]
# 命名分组
text = "2026-01-25"
pattern = r'(?P\d{4})-(?P\d{2})-(?P\d{2})'
match = re.match(pattern, text)
if match:
print(f"年份: {match.group('year')}")
print(f"月份: {match.group('month')}")
print(f"日期: {match.group('day')}")
# 非捕获分组
text = "apple, banana, orange"
pattern = r'(?:apple|banana), (\w+)'
match = re.search(pattern, text)
if match:
print(f"捕获: {match.group(1)}") # orange
预编译正则表达式
import re
# 预编译(性能更好)
pattern = re.compile(r'\d+')
# 使用预编译的模式
text = "Python 3.10 is awesome"
matches = pattern.findall(text)
print(matches) # ['3', '10']
# 多次使用
for text in ["Python 3.8", "Python 3.9", "Python 3.10"]:
version = pattern.findall(text)
print(f"{text}: {version}")
常用正则表达式符号
# . 匹配任意字符(除换行符)
re.search(r'P.y', 'Pay') # 匹配
# ^ 匹配字符串开头
re.search(r'^Hello', 'Hello World') # 匹配
# $ 匹配字符串结尾
re.search(r'World, 'Hello World') # 匹配
# * 匹配 0 次或多次
re.search(r'Py*', 'Pyyyyython') # 匹配
# + 匹配 1 次或多次
re.search(r'Py+', 'Pyyyyython') # 匹配
# ? 匹配 0 次或 1 次
re.search(r'Py?', 'Pthon') # 匹配
# {n} 匹配 n 次
re.search(r'\d{3}', '12345') # 匹配 '123'
# {n,m} 匹配 n 到 m 次
re.search(r'\d{1,3}', '12345') # 匹配 '123'
# [] 字符集
re.search(r'[Pp]ython', 'Python') # 匹配
# | 或
re.search(r'Python|Java', 'Python') # 匹配
# \d 数字, \w 单词字符, \s 空白字符
re.search(r'\d+', 'abc123') # 匹配 '123'
💡 提示:在正则表达式前加 r 前缀(原始字符串)可以避免转义字符的问题。