ToolkitX
知识库工具箱

正则表达式

re 模块、正则语法、常用模式

25min·进阶

01. re 模块基础

正则表达式是用于匹配字符串模式的强大工具。Python 的 re 模块提供了完整的正则表达式支持。
python
import re

text = "我的电话是 138-1234-5678,邮箱是 [email protected]"

# search - 搜索第一个匹配
phone = re.search(r"\d{3}-\d{4}-\d{4}", text)
if phone:
print(f"找到电话: {phone.group()}")

# findall - 查找所有匹配
numbers = re.findall(r"\d+", text)
print(numbers)  # ['138', '1234', '5678']

# sub - 替换
cleaned = re.sub(r"\d", "*", "电话: 13812345678")

02. 正则表达式语法

常用元字符:. 任意字符,^ 开头,$ 结尾,\d 数字,\w 字母数字下划线,\s 空白字符,* 0次或多次,+ 1次或多次。
python
import re

# 字符匹配
text = "abc 123 ABC"
print(re.findall(r"[a-z]+", text))    # ['abc']
print(re.findall(r"[0-9]+", text))    # ['123']

# 量词
text = "aab abbb a"
print(re.findall(r"ab*", text))   # ['aab', 'abbb', 'a']
print(re.findall(r"ab+", text))   # ['aab', 'abbb']

# 分组与捕获
date = "2026-06-30"
match = re.match(r"(\d{4})-(\d{2})-(\d{2})", date)
if match:
  print(match.groups())  # ('2026', '06', '30')

知识测验

1/5正确 0

re.search() 和 re.match() 的区别是什么?

下一节

并发编程

下一节