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

推荐订阅源

T
Threatpost
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
T
The Blog of Author Tim Ferriss
S
SegmentFault 最新的问题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 司徒正美
T
Tailwind CSS Blog
The Cloudflare Blog
The Last Watchdog
The Last Watchdog
PCI Perspectives
PCI Perspectives
博客园 - 聂微东
Stack Overflow Blog
Stack Overflow Blog
TaoSecurity Blog
TaoSecurity Blog
云风的 BLOG
云风的 BLOG
C
Cybersecurity and Infrastructure Security Agency CISA
O
OpenAI News
Recorded Future
Recorded Future
GbyAI
GbyAI
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Y
Y Combinator Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
量子位
博客园 - 叶小钗
V
Vulnerabilities – Threatpost
F
Full Disclosure
Recent Announcements
Recent Announcements
Vercel News
Vercel News
S
Schneier on Security
H
Heimdal Security Blog
Cisco Talos Blog
Cisco Talos Blog
V2EX - 技术
V2EX - 技术
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
B
Blog RSS Feed
宝玉的分享
宝玉的分享
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Privacy & Cybersecurity Law Blog
T
Threat Research - Cisco Blogs
G
Google Developers Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
爱范儿
爱范儿
IT之家
IT之家
大猫的无限游戏
大猫的无限游戏
C
Check Point Blog
N
Netflix TechBlog - Medium
S
Security @ Cisco Blogs
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Microsoft Azure Blog
Microsoft Azure Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Cyberwarzone
Cyberwarzone

博客园 - 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()