Python正则表达式使用


Python正则表达式终极指南:查找、替换与结果提取技巧

正则表达式是文本处理领域的核心工具之一,掌握其在Python中的应用能极大提升数据处理效率。本文将深入解析三大核心功能:文本查找内容替换结果提取,并附实战代码示例。


一、文本查找:精准定位目标内容

1. 单次匹配搜索

import re

text = "订单号:ABC123,金额:456.78元,客户:Alice"
pattern = r"金额:([\d.]+)元"  # 匹配金额数值

# 方法1:re.search()扫描全文
match = re.search(pattern, text)
if match:
    print(f"找到金额:{match.group(1)}")  # 输出:456.78

# 方法2:re.match()仅匹配开头
match_start = re.match(r"订单号:(\w+)", text)
print(match_start.group(1))  # 输出:ABC123

2. 批量结果提取

# 查找所有电话号码
contacts = "电话:021-12345678, 手机:13800138000, 传真:0755-87654321"
phone_pattern = r"\b\d{3,4}-\d{7,8}\b"

phones = re.findall(phone_pattern, contacts)
print(phones)  # 输出:['021-12345678', '0755-87654321']

二、内容替换:智能修改文本

1. 简单字符串替换

# 隐藏手机号中间四位
text = "联系方式:13800138000"
masked = re.sub(r"(\d{3})\d{4}(\d{4})", r"\1****\2", text)
print(masked)  # 输出:联系方式:138****8000

2. 动态逻辑替换

# 将温度全部升高5度
def add_temp(match):
    return str(int(match.group(1)) + 5)

weather = "今日温度:18℃ 明日:22℃"
updated = re.sub(r"(\d+)℃", add_temp, weather)
print(updated)  # 输出:今日温度:23℃ 明日:27℃

3. 复杂格式重组

# 重组日期格式(YYYYMMDD → DD/MM/YYYY)
log = "日志日期:20231231,更新:20240115"
formatted = re.sub(r"(\d{4})(\d{2})(\d{2})", r"\3/\2/\1", log)
print(formatted)  # 输出:日志日期:31/12/2023,更新:15/01/2024

三、结果提取:结构化捕获数据

1. 基础分组提取

# 提取带区号的电话号码
text = "客服热线:(021)1234-5678"
pattern = r"\((\d{3,4})\)(\d+-\d+)"

match = re.search(pattern, text)
if match:
    print(f"区号:{match.group(1)}")  # 输出:021
    print(f"号码:{match.group(2)}")  # 输出:1234-5678

2. 命名分组优化

# 使用命名分组提高可读性
pattern = r"(?P<area>\d{3,4})-(?P<number>\d{7,8})"
text = "紧急电话:010-12345678"

match = re.search(pattern, text)
if match:
    print(match.groupdict())  
    # 输出:{'area': '010', 'number': '12345678'}

3. 批量结果遍历

# 提取多组邮箱地址
emails = "工作邮箱:alice@company.com,私人邮箱:bob@gmail.com"
pattern = r"\b[\w.-]+@[\w.-]+\.\w+\b"

for match in re.finditer(pattern, emails):
    print(f"发现邮箱:{match.group()}")
    # 输出:alice@company.com 和 bob@gmail.com

四、高频问题解决方案

1. 错误处理技巧

try:
    match = re.search(r"\d+", "abc")
    print(match.group())
except AttributeError:
    print("无数字内容")  # 预防None对象访问

2. 性能优化方案

# 预编译高频使用正则
phone_regex = re.compile(r"\d{3}-\d{8}")
texts = ["电话:021-12345678", "传真:0755-87654321"]

for text in texts:
    if phone_regex.search(text):
        print("有效联系电话")

3. 特殊符号转义

# 匹配含点号的文件名
filename = "report_v1.2.pdf"
match = re.search(r"\bv\d+\.\d+\.pdf\b", filename)
print(match.group())  # 输出:v1.2.pdf

五、实战应用场景

1. 数据清洗

# 清理HTML标签
html = "<div>正文<p>核心内容</p></div>"
clean_text = re.sub(r"<[^>]+>", "", html)
print(clean_text)  # 输出:正文核心内容

2. 日志分析

# 提取IP地址
log = "访问者IP:192.168.1.1,时间:2023-12-31"
ip = re.search(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", log).group()
print(ip)  # 输出:192.168.1.1

3. 格式验证

# 验证邮箱格式
def is_valid_email(email):
    pattern = r"^[\w.-]+@[\w.-]+\.\w+$"
    return re.fullmatch(pattern, email) is not None

print(is_valid_email("test.user@example.com"))  # True

知识总结

功能 核心方法 最佳实践
文本查找 re.findall() re.finditer() 优先使用预编译正则对象
内容替换 re.sub() 复杂逻辑使用替换函数
结果提取 match.group() 命名分组提升可维护性
性能优化 re.compile() 高频正则预编译减少解析开销

掌握这些技巧后,您将能高效处理文本解析、数据清洗、日志分析等场景。建议结合具体业务需求,灵活组合不同方法实现精准的文本操控。

posted @ 2025-02-25 21:00  Gold_stein  阅读(84)  评论(0)    收藏  举报