当前位置:首页 > Python > 正文

Python re模块常用函数详解:高效处理文本与正则表达式 | Python正则表达式教程

Python re模块常用函数详解

高效处理文本与正则表达式的完全指南

正则表达式在Python中的重要性

Python的re模块提供了完整的正则表达式功能,是文本处理不可或缺的工具。无论您需要数据清洗、日志分析还是字符串匹配,re模块都能提供高效的解决方案。

核心优势:

  • 强大的模式匹配能力
  • 高效处理复杂文本结构
  • 简化字符串操作流程
  • 广泛应用于数据科学和网络爬虫

re模块核心函数概览

re.match()

从字符串起始位置匹配模式

re.search()

扫描整个字符串查找匹配

re.findall()

返回所有匹配项的列表

re.finditer()

返回匹配项的迭代器

re.sub()

替换字符串中的匹配项

re.compile()

预编译正则表达式对象

函数详解与代码示例

re.match(pattern, string) - 起始位置匹配

从字符串的起始位置匹配模式,如果起始位置匹配不成功则返回None。

import re

# 在字符串开始处匹配数字
result = re.match(r'\d+', '123abc')
if result:
    print("匹配成功:", result.group())  # 输出: 匹配成功: 123

# 起始位置不匹配
result = re.match(r'\d+', 'abc123')
print(result)  # 输出: None

re.search(pattern, string) - 全局搜索匹配

扫描整个字符串,返回第一个成功的匹配。

import re

text = "联系方式: 电话 123-4567-8901, 邮箱 contact@example.com"

# 搜索电话号码
phone_match = re.search(r'\d{3}-\d{4}-\d{4}', text)
if phone_match:
    print("找到电话:", phone_match.group())  # 输出: 找到电话: 123-4567-8901

# 搜索邮箱地址
email_match = re.search(r'[\w.-]+@[\w.-]+', text)
if email_match:
    print("找到邮箱:", email_match.group())  # 输出: 找到邮箱: contact@example.com

re.findall(pattern, string) - 查找所有匹配

返回字符串中所有匹配模式的子串组成的列表。

import re

# 提取字符串中所有数字
text = "苹果10个, 香蕉5根, 橙子8个"
numbers = re.findall(r'\d+', text)
print("找到的数字:", numbers)  # 输出: ['10', '5', '8']

# 提取HTML中的所有链接
html_content = '<a href="https://example.com">首页</a> <a href="/about">关于</a>'
links = re.findall(r'href="([^"]+)"', html_content)
print("所有链接:", links)  # 输出: ['https://example.com', '/about']

re.sub(pattern, repl, string) - 替换匹配项

将字符串中匹配模式的部分替换为指定字符串。

import re

# 隐藏电话号码中的部分数字
phone = "我的电话是: 13800138000"
hidden_phone = re.sub(r'(\d{3})\d{4}(\d{4})', r'\1****\2', phone)
print(hidden_phone)  # 输出: 我的电话是: 138****8000

# 日期格式转换
date_str = "今天是2023-07-15,明天是2023-07-16"
new_date = re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', date_str)
print(new_date)  # 输出: 今天是07/15/2023,明天是07/16/2023

re.compile(pattern) - 预编译正则表达式

将正则表达式编译成一个对象,提高多次使用时的效率。

import re

# 编译电子邮件正则表达式
email_pattern = re.compile(r'[\w.-]+@[\w.-]+\.\w+')

# 在多个文本中使用编译后的模式
text1 = "联系邮箱: user@example.com"
text2 = "客服邮箱: support@company.org"

match1 = email_pattern.search(text1)
if match1:
    print("邮箱1:", match1.group())  # 输出: 邮箱1: user@example.com

match2 = email_pattern.search(text2)
if match2:
    print("邮箱2:", match2.group())  # 输出: 邮箱2: support@company.org

高级技巧与最佳实践

分组捕获

使用圆括号()创建捕获组,提取匹配的子模式:

text = "姓名: 张三, 年龄: 30"
match = re.search(r'姓名: (\w+), 年龄: (\d+)', text)
if match:
    name, age = match.groups()
    print(f"{name}今年{age}岁")

非贪婪匹配

使用?实现非贪婪匹配,匹配尽可能少的字符:

html = "<div>内容1</div><div>内容2</div>"
# 贪婪匹配
greedy = re.findall(r'<div>.*</div>', html)
# 非贪婪匹配
non_greedy = re.findall(r'<div>.*?</div>', html)

性能优化

  • 对重复使用的模式使用re.compile()
  • 尽量使用具体字符代替宽泛通配符
  • 避免嵌套量词和回溯陷阱
  • 使用原子组(?>...)防止回溯

掌握re模块,提升文本处理能力

正则表达式是每个Python开发者必备的核心技能之一。通过本教程,您已掌握了re模块的核心函数和实用技巧。现在就开始在您的项目中应用这些知识吧!

Python正则表达式教程 © 2023 - 掌握文本处理的强大工具

发表评论