← Scrapy

正则表达式

核心函数

import re

re.search(pattern, string)   # 找第一个
re.findall(pattern, string)   # 找所有
re.sub(pattern, repl, string) # 替换
re.split(pattern, string)     # 分割
re.match(pattern, string)     # 从开头匹配

常用模式

\d      # 数字
\w      # 字母数字下划线
\s      # 空白
.       # 任意字符
*       # 0或多个
+       # 1或多个
?       # 0或1个
[]      # 字符集
()      # 分组

实战示例

# 提取邮箱
re.findall(r'[\w.-]+@[\w.-]+', text)

# 提取手机号
re.findall(r'1[3-9]\d{9}', text)

# 替换数字
re.sub(r'\d+', '#', 'abc123def456')  # abc#def#

编译优化

# 预编译提升性能
pattern = re.compile(r'\d+')
pattern.findall(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.14 is awesome"
matches = pattern.findall(text)
print(matches)  # ['3', '10']

# 多次使用
for text in ["Python 3.14", "Python 3.14", "Python 3.14"]:
    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 前缀(原始字符串)可以避免转义字符的问题。
← Scrapy