约 1586 字
约 8 分钟
在 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, "user@example.com"):
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("user@example.com"):
print("有效邮箱")
创建于 2025/5/13
更新于 2025/5/21