Python 正则表达式核心用法与实战示例
字符串处理是编程中的基础且高频场景,正则表达式(Regular Expression)提供了简洁高效的文本匹配方案。Python 内置的 re 模块为开发者提供了完整的正则支持。本文将系统梳理 Python 正则表达式的常用语法、函数及实战技巧,帮助读者掌握这一核心工具。
Python 正则表达式的核心用法与实战技巧。内容涵盖基础匹配函数 search 与 findall,字符类如数字与小数匹配,量星与锚点的运用,以及分组捕获机制。同时讲解了 split 与 sub 函数的应用,并补充了原始字符串、预编译模式等最佳实践。文中提供了邮箱、手机号及 URL 提取等常见场景的代码示例,旨在帮助开发者高效解决文本处理问题。

字符串处理是编程中的基础且高频场景,正则表达式(Regular Expression)提供了简洁高效的文本匹配方案。Python 内置的 re 模块为开发者提供了完整的正则支持。本文将系统梳理 Python 正则表达式的常用语法、函数及实战技巧,帮助读者掌握这一核心工具。
使用 re.search() 在字符串中查找第一个符合模式的位置。如果找到,返回一个 Match 对象;否则返回 None。
import re
s = 'i love python very much'
pattern = 'python'
result = re.search(pattern, s)
if result:
print(f"匹配位置:{result.span()}") # 输出:(7, 13)
print(f"匹配内容:{result.group()}") # 输出:python
使用 re.finditer() 或 re.findall() 获取所有匹配结果。
s = '山东省潍坊市青州第 1 中学高三 1 班'
pattern = '1'
# finditer 返回迭代器,包含 Match 对象
for match in re.finditer(pattern, s):
print(f"索引:{match.span()}, 内容:{match.group()}")
# 输出:
# 索引:(9, 10), 内容:1
# 索引:(14, 15), 内容:1
\d 代表任意数字(等价于 [0-9]),配合量词可匹配多位数。
s = '一共 20 行代码运行时间 13.59s'
pattern = r'\d+' # \d+ 表示匹配一个或多个数字
matches = re.findall(pattern, s)
print(matches) # ['20', '13', '59']
通过组合 \d 和转义点号 \. 来匹配浮点数。
s = '一共 20 行代码运行时间 13.59s'
pattern = r'\d+\.?\d*' # ? 表示前一个字符出现 0 次或 1 次
matches = re.findall(pattern, s)
print(matches) # ['20', '13.59']
*: 0 次或多次+: 1 次或多次?: 0 次或 1 次{n}: 恰好 n 次{n,}: 至少 n 次{n,m}: n 到 m 次^ 匹配字符串开头,$ 匹配字符串结尾。注意在多行模式下行为可能不同。
s = 'This module provides regular expression matching operations similar to those found in Perl'
pattern = r'^[emrt]' # 查找以 e, m, r, t 开头的单词
matches = re.findall(pattern, s)
print(matches) # [],因为首字母是 T
使用 re.I (或 re.IGNORECASE) 标志忽略大小写差异。
s = 'This module provides regular expression matching operations similar to those found in Perl'
pattern = r'^[emrt]'
# 编译时添加 IGNORECASE 标志
compiled = re.compile(pattern, re.I)
result = compiled.search(s)
if result:
print(result.group()) # 输出:T
利用空白字符 和字母范围 [a-zA-Z] 进行分割提取。
s = 'This module provides regular expression matching operations similar to those found in Perl'
pattern = r'\s([a-zA-Z]+)' # 捕获空格后的单词
matches = re.findall(pattern, s)
print(matches)
# ['module', 'provides', 'regular', ...]
使用 ? 使空格变为可选,从而捕获第一个单词。
s = 'This module provides regular expression matching operations similar to those found in Perl'
pattern = r'\s?([a-zA-Z]+)' # 空格可选
matches = re.findall(pattern, s)
print(matches)
# ['This', 'module', 'provides', ...]
使用 (?:...) 进行分组但不捕获内容,常用于优化性能。
s = 'color red and color blue'
pattern = r'(?:red|blue)'
matches = re.findall(pattern, s)
print(matches) # ['red', 'blue']
使用 re.split() 按正则模式分割字符串。
s = 'This module provides regular expression matching operations similar to those found in Perl'
pattern = r'\s+'
words = re.split(pattern, s)
print(words) # ['This', 'module', 'provides', ...]
使用 re.sub() 将匹配到的部分替换为新字符串。
s = '价格:100 元,折扣后:80 元'
pattern = r'(\d+) 元'
def replace_price(match):
price = int(match.group(1))
return f'{price * 0.8}元'
result = re.sub(pattern, replace_price, s)
print(result) # 价格:80.0 元,折扣后:64.0 元
在定义正则表达式时,建议使用 Python 的原始字符串(Raw String),即在引号前加 r。这可以避免反斜杠被转义。
# 推荐
pattern = r'\d+'
# 不推荐(需要双反斜杠)
pattern = '\\\d+'
对于重复使用的复杂正则,使用 re.compile() 预编译可以提高性能。
import re
pattern = re.compile(r'\w+@\w+\.com')
result = pattern.search('[email protected]')
email_pattern = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+'
phone_pattern = r'1[3-9]\d{9}'
url_pattern = r'https?://(?:www\.)?[a-zA-Z0-9.-]+'
Python 的正则表达式功能强大,涵盖了从基础匹配到高级替换的各种场景。掌握 search, findall, split, sub 等核心函数,理解字符类、量词、分组及锚点的含义,能够显著提升文本处理效率。在实际开发中,建议优先使用原始字符串定义模式,对复杂逻辑进行预编译,并注意特殊字符的转义问题,以确保代码的健壮性与可维护性。
通过上述示例与实践,读者应能构建起对 Python 正则表达式的系统性认知,并灵活应用于日志分析、数据清洗及表单验证等实际业务场景中。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online