1586

8 分钟

#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, "user@example.com"): print("有效邮箱")

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#文本搜索

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))

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#文本替换

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

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#文本分割

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

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#编译正则表达式

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

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("有效邮箱")

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

创建于 2025/5/13

更新于 2025/5/21