惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Schneier on Security
博客园 - 叶小钗
博客园 - 三生石上(FineUI控件)
C
Cybersecurity and Infrastructure Security Agency CISA
Engineering at Meta
Engineering at Meta
Google DeepMind News
Google DeepMind News
酷 壳 – CoolShell
酷 壳 – CoolShell
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园_首页
T
Threat Research - Cisco Blogs
C
Cisco Blogs
Recent Announcements
Recent Announcements
S
Securelist
N
Netflix TechBlog - Medium
The Register - Security
The Register - Security
P
Privacy & Cybersecurity Law Blog
宝玉的分享
宝玉的分享
D
Darknet – Hacking Tools, Hacker News & Cyber Security
L
LINUX DO - 热门话题
T
Tor Project blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
月光博客
月光博客
AWS News Blog
AWS News Blog
P
Proofpoint News Feed
博客园 - 司徒正美
L
LINUX DO - 最新话题
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
H
Help Net Security
Spread Privacy
Spread Privacy
PCI Perspectives
PCI Perspectives
Project Zero
Project Zero
I
Intezer
T
The Blog of Author Tim Ferriss
有赞技术团队
有赞技术团队
The Last Watchdog
The Last Watchdog
C
Check Point Blog
Blog — PlanetScale
Blog — PlanetScale
B
Blog RSS Feed
MyScale Blog
MyScale Blog
V
Vulnerabilities – Threatpost
Recorded Future
Recorded Future
T
Tenable Blog
Jina AI
Jina AI
D
DataBreaches.Net
阮一峰的网络日志
阮一峰的网络日志

博客园 - pcwanli

Python批量将Word文档(.doc)转换为.docx格式的完整实现步骤 Linux下版本控制器(SVN) -命令行客户端 linux svn 命令 Qwen3-VL视频科技:内容审核系统搭建 svn update 出现Skipped 'feifazuzhi' -- Node remains in conflict处理方法 linux redis.service如何编写 深入php redis pconnect PHP中使用Redis长连接笔记 python happybase 批量读取 如何用phpredis持久化连接pconnect方法提升应用响应速度 python处理常见格式压缩包文件的全指南 Python编程:happybase读写HBase数据库 python redis zset 按分值获取记录 hbase日志如何清理 hbase日志清理 Python的time.strftime()方法 python re.sub第二参数,前值如何引用 【Python】基于python实现Windows Service程序 python解析url参数 提取网页源码头信息的正则表达式 PHP字符串分割:explode()函数详解与应用 python requests get请求禁用自动解压 python importlib动态模块加载遇到is not a package错误,解决方法。 用Python处理HTML转义字符的5种方式 pymongo批量更新bulk_write php mongodb操作 PHP 通过 Thrift 操作 Hbase 使用thrift的php版本操作hbase数据库 PHP通过Thrift操作Hbase
Python正则表达式替换(re.sub)的6种典型应用场景
pcwanli · 2026-03-15 · via 博客园 - pcwanli

来源:https://comate.baidu.com/zh/page/ghk02f7u8qi

在Python文本处理中,re.sub()函数通过正则表达式实现灵活的文本替换。本文通过6个典型场景演示其核心用法,涵盖基础替换、分组引用、函数式处理等高级功能。

基础文本替换

最基础的替换场景,直接匹配目标字符串并替换为新内容。

import re def demo_basic_replace(): """基础替换示例""" text = "今天是2023年12月15日" new_text = re.sub(r"2023", "2024", text) print(f"基础替换: {new_text}") # 输出:今天是2024年12月15日

分组引用替换

通过正则分组捕获文本片段,并使用反向引用重组结果。

def demo_group_replace(): """分组替换示例""" text = "张三 李四 王五" new_text = re.sub(r"(\w+) (\w+)", r"\2 \1", text) print(f"分组替换: {new_text}") # 输出:李四 张三 王五

函数式动态替换

通过回调函数实现复杂替换逻辑,支持动态计算替换内容。

def demo_function_replace(): """函数式替换示例""" def double_number(match): number = int(match.group()) return str(number * 2) text = "数字: 5, 10, 15" new_text = re.sub(r"\d+", double_number, text) print(f"函数替换: {new_text}") # 输出:数字: 10, 20, 30

电话号码格式化

标准化不同格式的电话号码为统一格式。

def demo_phone_format(): """电话号码格式化""" def format_phone(text): pattern = r"(\d{3})[-.\s]?(\d{3})[-.\s]?(\d{4})" return re.sub(pattern, r"(\1) \2-\3", text) phones = "联系: 123-456-7890, 123.456.7890, 123 456 7890" print(f"电话格式化: {format_phone(phones)}") # 输出:(123) 456-7890

HTML标签清理

移除HTML文档中的所有标签,提取纯文本内容。

def demo_html_clean(): """HTML标签清理""" def remove_tags(text): return re.sub(r"<[^>]+>", "", text) html = "<h1>标题</h1><p>这是一个<strong>段落</strong></p>" print(f"HTML清理: {remove_tags(html)}") # 输出:标题这是一个段落

敏感数据脱敏

对身份证号、手机号等敏感信息进行部分隐藏处理。

def demo_data_mask(): """数据脱敏处理""" def mask_data(text): text = re.sub(r"(\d{4})\d{8}(\d{4})", r"\1********\2", text) # 身份证 text = re.sub(r"(\d{3})\d{4}(\d{4})", r"\1****\2", text) # 手机号 return text sensitive = "身份证: 510123199001011234, 手机: 13800138000" print(f"数据脱敏: {mask_data(sensitive)}") # 输出:身份证: 5101********1234, 手机: 138****8000

完整示例代码

# regex_replace_demo.py import re if __name__ == "__main__": demo_basic_replace() demo_group_replace() demo_function_replace() demo_phone_format() demo_html_clean() demo_data_mask()