国际访客建议访问 Primers 编程伙伴 国际版站点 > Python 教程 > 使用 以获得更好的体验。

# Python 正则表达式的使用

在 Python 中通过 re 模块使用正则表达式。由于正则表达式本身存在转义语法,因此通常使用 Python 的 原始字符串 编写正则表达式,避免多次转义。

接口 说明 示例
match 检查字符串是否匹配正则表达式 查看
search 查找字符串中匹配正则表达的子串 查看
sub 将字符串中匹配正则表达的子串进行替换 查看
split 通过字符串中匹配正则表达的子串分割字符串 查看
compile 编译正则表达式 查看

# 匹配校验

运行示例

import re

# 验证电子邮件格式
email_pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
if re.match(email_pattern, "[email protected]"):
    print("有效邮箱")

# 文本搜索

运行示例

import re

text = "订单号: 12345, 日期: 2023-08-15"
match = re.search(r'订单号: (\d+), 日期: (\d{4}-\d{2}-\d{2})', text)
if match:
    print(0, match.group(0))
    print(1, match.group(1))
    print(2, match.group(2))

# 文本替换

运行示例

import re

text = "用户名:user 密码:123456"
hidden = re.sub(r'\d{6}', '******', text)
print(hidden)

# 文本分割

运行示例

import re

data = "苹果,香蕉,橙子,葡萄"
fruits = re.split(r',\s*', data)  # 按逗号分割,允许逗号后有空格
print(fruits)  # 输出: ['苹果', '香蕉', '橙子', '葡萄']

# 编译正则表达式

编译后可以重复使用,效率更高。

运行示例

import re

# 验证电子邮件格式
email_pattern = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
if email_pattern.match("[email protected]"):
    print("有效邮箱")
本文 更新于: 2025-06-19 01:15:36 创建于: 2025-06-19 01:15:36