Python 正则表达式高级应用指南
正则表达式是一种强大的文本模式匹配工具,在 Python 中,我们可以使用 re 模块来进行正则表达式的操作。以下是一些高级的正则表达式应用示例:
复杂的模式匹配
import re
text = "Hello, my email is example@example.com and my phone number is 123-456-7890."
email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
phone_pattern = r'\d{3}-\d{3}-\d{4}'
emails = re.findall(email_pattern, text)
phones = re.findall(phone_pattern, text)
print("Emails found:", emails)
print("Phones found:", phones)
在上述代码中,我们定义了两个正则表达式模式:一个用于匹配电子邮件地址,另一个用于匹配电话号码。
分组和提取
import re
text = "The price of the product is $12.99."
pattern = r'(\$\d+\.\d{2})'
match = re.search(pattern, text)
if match:
price = match.group(1)
print("Price found:", price)
这里使用了分组来提取匹配的部分。
替换操作
import re
text = "Hello, World! How are you?"
pattern = r'World'
replaced_text = re.sub(pattern, "Python", text)
print("Replaced text:", replaced_text)
通过 re.sub() 函数可以进行替换操作。
多行匹配
import re
text = """
Line 1: This is the first line.
Line 2: This is the second line.
Line 3: This is the third line.
"""
pattern = r'Line \d+'
matches = re.findall(pattern, text, re.MULTILINE)
print("Matches found:", matches)
使用 re.MULTILINE 标志可以进行多行匹配。
贪婪与非贪婪模式
import re
text = "<html><head><title>Title</title></head></html>"
pattern_greedy = r'<.*>'
pattern_nongreedy = r'<.*?>'
match_greedy = re.search(pattern_greedy, text)
match_nongreedy = re.search(pattern_nongreedy, text)
print("Greedy match:", match_greedy.group())
print("Non-greedy match:", match_nongreedy.group())
演示了贪婪模式和非贪婪模式的区别。
正则表达式的应用非常广泛,可以根据具体的需求灵活运用这些高级技巧来处理各种文本模式匹配问题。
本文代码转自:https://www.wodianping.com/app/2024-10/48515.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统