常用元字符

表达式含义示例
.任意字符(除换行)a.c 匹配 abc
\d数字\d{3} 匹配 123
\w字母数字下划线\w+
\s空白符\s+
[]字符集合[a-z0-9]
^ $开头/结尾^start$
* + ?0或多 / 1或多 / 0或1a* a+ a?

re 模块

import re

# findall: 返回所有匹配
re.findall(r"\d+", "价格 100 和 200")

# search: 找第一个
m = re.search(r"(\d{4})-(\d{2})-(\d{2})", "2026-10-11")
m.group(1)  # 2026

# match: 从开头匹配
re.match(r"^\d", "123abc")

# sub: 替换
re.sub(r"\s+", " ", "a   b   c")  # 'a b c'

贪婪与非贪婪

# 贪婪: 尽可能多
re.findall(r"<.+>", "text")  # ['text']

# 非贪婪: 加 ?
re.findall(r"<.+?>", "text")  # ['', '']

实战:解析访问日志 IP

line = '140.179.125.104 - - [02/Oct/2026:10:30:51] "GET /js/app.js" 200'
m = re.search(r"(\d+\.\d+\.\d+\.\d+) .*\[(.+?)\] "(\w+) ([^ ]+)" (\d+)", line)
print(m.groups())
建议:正则复杂时加注释或拆成多个小正则,用在线工具先验证。