re 用法
🧪 示例:不使用 vs 使用 re.compile()
🧱 普通用法(不推荐重复用正则时)
1 2 3 4
| import re
re.search(r"\d+", "编号123") re.search(r"\d+", "订单456")
|
🚀 推荐写法(使用 re.compile)
1 2 3 4 5 6
| import re
pattern = re.compile(r"\d+")
print(pattern.search("编号123")) print(pattern.search("订单456"))
|
🎯 优势总结
| 优点 |
说明 |
| ✅ 提高性能 |
编译一次后多次使用,比每次都重新解析正则更高效 |
| ✅ 增强可读性 |
把正则表达式独立定义,更清晰 |
| ✅ 支持 flags 参数 |
可以传入 re.IGNORECASE 等模式开关 |
🎈 带 flags 示例(忽略大小写)
1 2 3 4
| pattern = re.compile(r"hello", re.IGNORECASE)
match = pattern.search("HeLLo World") print(match.group())
|
re 函数的用法区别
| 方法 |
用途简介 |
匹配位置 |
返回类型 |
| re.search |
搜索字符串中第一次出现正则表达式的模式 |
从字符串开头开始匹配 |
match 对象 |
| re.match |
从字符串开头匹配正则表达式的模式 |
从字符串开头开始匹配 |
match 对象 |
| re.findall |
搜索字符串,以列表形式返回全部能匹配的子串 |
从字符串开头开始匹配 |
列表(字符串或元组) |
| re.split |
以正则表达式为分隔符拆分字符串 |
从字符串开头开始匹配 |
列表(字符串或元组) |
| re.sub |
使用正则表达式替换字符串中每一个匹配的子串后返回替换后的字符串 |
从字符串开头开始匹配 |
字符串 |
Match 对象# Match 对象是 re 模块中匹配操作返回的结果对象,包含匹配信息
以下是一个简单的示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import re
text = "Hello, my email is example@example.com" pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"
match = re.search(pattern, text)
if match: print(f"找到匹配: {match.group()}") print(f"匹配的起始位置: {match.start()}") print(f"匹配的结束位置: {match.end()}") print(f"匹配的字符串片段: {text[match.start():match.end()]}") else: print("未找到匹配")
|
match
1 2 3 4 5
| result = re.match(r'\d+', '123abc') if result: print(result.group()) else: print("No match")
|
search
1 2 3 4 5
| result = re.search(r'\d+', '123abc') if result: print(result.group()) else: print("No match")
|
findall
1 2 3 4 5
| result = re.findall(r'\d+', '123abc') if result: print(result) else: print("No match")
|
split
1 2 3 4 5
| result = re.split(r'\d+', '123abc') if result: print(result) else: print("No match")
|
sub
1 2 3 4 5
| result = re.sub(r'\d+', 'abc', '123abc') if result: print(result) else: print("No match")
|