Python 中的 re
模块用于进行正则表达式操作:
1. 匹配模式
import re
text = "Hello, world!"
pattern = r"world"
# 检查文本中是否包含模式
match = re.search(pattern, text)
if match:
print("模式匹配成功!")
else:
print("模式匹配失败。")
2. 替换
import re
text = "I have a cat and a dog."
pattern = r"cat"
replacement = "rabbit"
# 替换匹配的部分
new_text = re.sub(pattern, replacement, text) print(new_text)
# 输出:I have a rabbit and a dog.
3. 分割
import re
text = "apple;banana;cherry"
pattern = r";" # 使用分隔符分割字符串
parts = re.split(pattern, text)
print(parts) # 输出:['apple', 'banana', 'cherry']
4. 提取
import re
text = "My email is example@example.com."
pattern = r"\b\w+@\w+\.\w+\b"
# 提取所有匹配的邮箱地址
emails = re.findall(pattern, text) print(emails)
# 输出:['example@example.com']
这些示例展示了 re
模块在处理文本和模式匹配时的基本用法。