Python中正则表达式通过re模块实现,核心函数包括re.search、re.match、re.findall、re.sub和re.compile,配合原始字符串r""避免转义问题,可高效处理文本匹配、查找、替换与分割。
Python中正则表达式的使用,核心在于利用其内置的
re
在Python里,正则表达式的一切都围绕着
re
最基础的几个函数包括:
re.search(pattern, string, flags=0)
MatchObject
None
立即学习“Python免费学习笔记(深入)”;
import re text = "我的电话是138-0000-1234,工作电话是010-8765-4321。" pattern = r"\d{3}-\d{4}-\d{4}" # 匹配手机号格式 match = re.search(pattern, text) if match: print(f"找到的手机号: {match.group()}") # 输出:找到的手机号: 138-0000-1234
re.match(pattern, string, flags=0)
MatchObject
None
text = "Hello World" pattern = r"Hello" match = re.match(pattern, text) if match: print(f"从开头匹配到: {match.group()}") # 输出:从开头匹配到: Hello pattern_fail = r"World" match_fail = re.match(pattern_fail, text) if not match_fail: print("World不在开头,所以match失败") # 输出:World不在开头,所以match失败
re.findall(pattern, string, flags=0)
text = "数字123和数字456都在这里。" pattern = r"\d+" # 匹配一个或多个数字 numbers = re.findall(pattern, text) print(f"找到的所有数字: {numbers}") # 输出:找到的所有数字: ['123', '456']
re.sub(pattern, repl, string, count=0, flags=0)
repl
text = "今天是2023年10月26日。" pattern = r"\d+" new_text = re.sub(pattern, "XXXX", text) print(f"替换后的文本: {new_text}") # 输出:替换后的文本: 今天是XXXX年XXXX月XXXX日。 # 使用函数作为替换项 def replace_func(match_obj): return str(int(match_obj.group()) + 1) # 把数字加1 new_text_func = re.sub(pattern, replace_func, text) print(f"函数替换后的文本: {new_text_func}") # 输出:函数替换后的文本: 今天是2024年11月27日。
re.compile(pattern, flags=0)
Pattern
email_pattern = re.compile(r"[\w.-]+@[\w.-]+") # 编译一个简单的邮箱匹配模式 text_with_emails = "联系我:test@example.com 或 support@domain.org" emails = email_pattern.findall(text_with_emails) print(f"找到的邮箱: {emails}") # 输出:找到的邮箱: ['test@example.com', 'support@domain.org']
关于原始字符串(Raw String)r"..."
\
\
\d
\
r"..."
r"\d"
\d
谈到正则表达式,那些
以上就是Python中正则表达式怎么用 Python中正则表达式指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号