import re
# 示例代码:使用正则表达式替换字符串中的内容
# 原始字符串
text = "Hello, my email is example@example.com and my phone number is 123-456-7890."
# 使用正则表达式替换电子邮件地址为 "[EMAIL]"
email_pattern = r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+"
new_text = re.sub(email_pattern, "[EMAIL]", text)
# 使用正则表达式替换电话号码为 "[PHONE]"
phone_pattern = r"\d{3}-\d{3}-\d{4}"
new_text = re.sub(phone_pattern, "[PHONE]", new_text)
print("原始文本:", text)
print("替换后的文本:", new_text)
re
模块,它是 Python 中用于处理正则表达式的标准库。text
。email_pattern
用于匹配电子邮件地址。phone_pattern
用于匹配电话号码(格式为 xxx-xxx-xxxx
)。re.sub()
函数进行替换:re.sub(email_pattern, "[EMAIL]", text)
将所有匹配 email_pattern
的部分替换为 [EMAIL]
。re.sub(phone_pattern, "[PHONE]", new_text)
将所有匹配 phone_pattern
的部分替换为 [PHONE]
。希望这个示例能帮助你理解如何在 Python 中使用正则表达式进行字符串替换。
下一篇:python重命名文件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站