Python正则表达式实战指南 从字符串匹配到数据清洗的常见问题与解决方案

正则表达式(Regular Expression,简称 regex 或 regexp)是Python中处理字符串的强大工具,它使用一种特殊的语法规则来描述和匹配字符串的模式。在数据清洗、文本处理、日志分析等场景中,正则表达式扮演着不可或缺的角色。然而,正则表达式的学习曲线较为陡峭,语法复杂且容易出错。本指南将从基础到进阶,通过实战案例详细讲解Python正则表达式的使用方法,帮助你解决从字符串匹配到数据清洗的常见问题。
1. Python正则表达式基础
在使用Python正则表达式之前,首先需要了解Python内置的
re
模块。该模块提供了正则表达式操作的所有核心功能。
1.1 常用函数介绍
re.match()
: 从字符串的起始位置匹配一个模式,如果起始位置匹配成功,则返回匹配对象,否则返回None。
re.search()
: 扫描整个字符串并返回第一个成功的匹配。
re.findall()
: 查找字符串中所有匹配的子串,并以列表形式返回。
re.finditer()
: 查找字符串中所有匹配的子串,并返回一个迭代器,每个迭代元素都是一个匹配对象。
re.sub()
: 替换字符串中所有匹配的子串。
1.2 基础示例
import re

text = “Python is a great programming language. Python is easy to learn.”

# match: 从开头匹配
match_result = re.match(r”Python”, text)
print(“match结果:”, match_result.group() if match_result else “None”)

# search: 搜索第一个匹配
search_result = re.search(r”Python”, text)
print(“search结果:”, search_result.group() if search_result else “None”)

# findall: 查找所有匹配
findall_result = re.findall(r”Python”, text)
print(“findall结果:”, findall_result)

# finditer: 查找所有匹配并返回迭代器
finditer_result = re.finditer(r”Python”, text)
for match in finditer_result:
print(“finditer结果:”, match.group(), “位置:”, match.start())

# sub: 替换
sub_result = re.sub(r”Python”, “Java”, text)
print(“sub结果:”, sub_result)
输出结果
:
match结果: Python
search结果: Python
findall结果: [‘Python’, ‘Python’]
finditer结果: Python 位置: 0
finditer结果: Python 位置: 30
sub结果: Java is a great programming language. Java is easy to learn.
注意
:
re.match()
只从字符串开头匹配,如果开头不匹配,即使后面有匹配的内容也会返回None。
re.search()
会扫描整个字符串,但只返回第一个匹配。
re.findall()
返回所有匹配的子串列表,如果正则表达式中有分组,则返回分组元组的列表。
re.finditer()
返回匹配对象的迭代器,可以获取匹配的位置等详细信息。
re.sub()
用于替换匹配的子串,第一个参数是模式,第二个是替换内容,第三个是原字符串。
2. 正则表达式语法规则
正则表达式的语法由普通字符(如字母、数字)和特殊字符(元字符)组成。下面介绍常用的语法规则。
2.1 元字符
元字符
描述
示例
.
匹配除换行符外的任意字符
a.c
匹配 “abc”, “aac”, “a c”
^
匹配字符串的开头
^Hello
匹配以 “Hello” 开头的字符串
$
匹配字符串的结尾
world$
匹配以 “world” 结尾的字符串
*
匹配前一个字符0次或多次
ab*c
匹配 “ac”, “abc”, “abbc”
+
匹配前一个字符1次或多次
ab+c
匹配 “abc”, “abbc”
?
匹配前一个字符0次或1次
ab?c
匹配 “ac”, “abc”
{n}
匹配前一个字符n次
a{3}c
匹配 “aaac”
{n,}
匹配前一个字符至少n次
a{3,}c
匹配 “aaac”, “aaaac”
{n,m}
匹配前一个字符n到m次
a{3,5}c
匹配 “aaac”, “aaaac”, “aaaaac”
[]
匹配括号内的任意一个字符
[abc]
匹配 “a”, “b”, “c”
[^]
匹配不在括号内的任意一个字符
[^abc]
匹配除a,b,c外的字符
|
或运算符
a|b
匹配 “a” 或 “b”
()
分组,捕获内容
(abc)+
匹配 “abc”, “abcabc”
2.2 预定义字符集
符号
描述
示例
\d
匹配任意数字,等价于
[0-9]
\d+
匹配一个或多个数字
\D
匹配任意非数字
\D+
匹配一个或多个非数字
\w
匹配字母、数字、下划线,等价于
[a-zA-Z0-9_]
\w+
匹配单词
\W
匹配非字母数字下划线
\W+
匹配非单词字符
\s
匹配任意空白字符(空格、制表符、换行符等)
\s+
匹配一个或多个空白
\S
匹配任意非空白字符
\S+
匹配非空白字符
2.3 转义字符
在正则表达式中,如果要匹配元字符本身,需要使用反斜杠
\
进行转义。例如,匹配点号
.
需要写成
\.
,匹配反斜杠
\
需要写成
\\
。
import re

text = “a.b.c”
# 匹配点号
result = re.findall(r”\.”, text)
print(“匹配点号:”, result) # 输出: [‘.’, ‘.’]

# 匹配反斜杠
text2 = “a\b\c”
# 注意:在Python字符串中,\b是退格符,所以需要写成”a\\b\\c”或使用原始字符串
text2 = r”a\b\c”
result2 = re.findall(r”\\”, text2)
print(“匹配反斜杠:”, result2) # 输出: [‘\\’, ‘\\’]
2.4 分组与捕获
使用
()
可以对模式进行分组,并捕获匹配的内容。捕获的内容可以通过匹配对象的
group()
方法获取。
import re

text = “我的电话是138-1234-5678,另一个是139-8765-4321″
pattern = r”(\d{3})-(\d{4})-(\d{4})”
matches = re.findall(pattern, text)
print(“分组捕获:”, matches) # 输出: [(‘138’, ‘1234’, ‘5678’), (‘139’, ‘8765’, ‘4321’)]

# 使用group获取匹配对象
for match in re.finditer(pattern, text):
print(“完整匹配:”, match.group(0))
print(“第一组:”, match.group(1))
…
print(“第二组:”, match.group(2))
print(“第三组:”, match.group(3))
2.5 非捕获分组
有时我们只需要分组的功能,但不需要捕获内容,可以使用
(?:)
语法。
import re

text = “abc123def456″
pattern = r”(?:abc|def)(\d+)”
matches = re.findall(pattern, text)
print(“非捕获分组:”, matches) # 输出: [‘123’, ‘456’],只捕获数字部分
2.6 贪婪与非贪婪
正则表达式默认是贪婪匹配,即尽可能多地匹配字符。在量词后加
?
可以变为非贪婪匹配。
import re

text = “

content

”
# 贪婪匹配
greedy = re.findall(r”<.*>“, text)
print(“贪婪匹配:”, greedy) # 输出: [‘

content

‘]

# 非贪婪匹配
non_greedy = re.findall(r”<.*?>“, text)
print(“非贪婪匹配:”, non_greedy) # 输出: [‘

‘, ‘

‘]
2.7 断言(Lookaround)
断言是零宽断言,用于查找在某些内容之前或之后的内容,但不包含这些内容本身。
零宽正向先行断言
(?=…)
: 匹配后面是…的内容
零宽负向先行断言
(?!…)
: 匹配后面不是…的内容
零宽正向后行断言
(?<=...) : 匹配前面是…的内容 零宽负向后行断言 (? {normalize_date(date)}”)
输出
:
2024/01/15 -> 2024-01-15
01-15-2024 -> 2024-01-15
2024年01月15日 -> 2024-01-15
2024/1/5 -> 2024-01-05
4.3 案例3:提取HTML中的文本内容
问题
: 需要从HTML字符串中提取纯文本内容,去除所有标签。
解决方案
: 使用正则表达式替换HTML标签。
import re

html = “””

标题

这是段落内容,包含强调文本。

链接

“””

# 去除所有HTML标签
text = re.sub(r’<[^>]+>’, ”, html)
print(“提取的文本:”, text.strip())
输出
:
提取的文本: 标题
这是段落内容,包含强调文本。
链接
注意
: 对于复杂的HTML解析,建议使用专门的库如BeautifulSoup,因为正则表达式可能无法处理嵌套标签或特殊情况。
4.4 案例4:清理用户输入中的特殊字符
问题
: 用户输入可能包含不需要的特殊字符、表情符号等,需要清理。
解决方案
: 使用正则表达式保留允许的字符。
import re

def clean_user_input(text, allow_chars=r’a-zA-Z0-9\s’):
“””
清理用户输入,只保留指定字符
:param text: 输入文本
:param allow_chars: 允许的字符集(正则表达式字符类)
:return: 清理后的文本
“””
# 构建正则表达式:匹配不在允许范围内的字符
pattern = f'[^{allow_chars}]’
return re.sub(pattern, ”, text)

# 示例:只保留字母、数字和空格
user_input = “Hello! @#$%^&*() 世界 123 😊”
cleaned = clean_user_input(user_input)
print(“原始输入:”, user_input)
print(“清理后:”, cleaned)

# 只保留中文、字母和数字
cleaned_cn = clean_user_input(user_input, r’a-zA-Z0-9\s\u4e00-\u9fff’)
print(“保留中文:”, cleaned_cn)
输出
:
原始输入: Hello! @#$%^&*() 世界 123 😊
清理后: Hello 世界 123
保留中文: Hello 世界 123
解释
:
[^…]
:匹配不在括号内的字符
\u4e00-\u9fff
:Unicode范围,匹配中文字符
表情符号😊被移除,因为它不在允许的字符范围内
4.5 案例5:批量替换文本中的占位符
问题
: 模板文本中包含多个占位符如
{name}
、
{email}
,需要根据字典替换为实际值。
解决方案
: 使用
re.sub()
配合函数进行替换。
import re

def replace_placeholders(template, data):
“””
替换模板中的占位符
:param template: 模板字符串,如”Hello {name}, your email is {email}”
:param data: 字典,包含占位符对应的值
:return: 替换后的字符串
“””
def replacer(match):
key = match.group(1)
return data.get(key, match.group(0))

pattern = r’\{(\w+)\}’
return re.sub(pattern, replacer, template)

# 示例
template = “尊敬的{username},您的订单{order_id}已发货,预计{date}送达。”
data = {
“username”: “张三”,
“order_id”: “20240115001”,
“date”: “2024-01-20”
}

result = replace_placeholders(template, data)
print(“模板:”, template)
print(“替换后:”, result)
输出
:
模板: 尊敬的{username},您的订单{order_id}已发货,预计{date}送达。
替换后: 尊敬的张三,您的订单20240115001已发货,预计2024-01-20送达。
解释
:
r’\{(\w+)\}’
:匹配
{占位符}
格式,
\w+
匹配字母数字下划线,
()
捕获占位符名称
replacer
函数:根据捕获的占位符名称从字典中获取值进行替换
re.sub()
:对每个匹配调用
replacer
函数
5. 性能优化与最佳实践
5.1 编译正则表达式
如果同一个正则表达式需要多次使用,应该先编译,以提高性能。
import re

# 不推荐:每次调用都重新编译
def find_emails(text):
return re.findall(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}’, text)

# 推荐:预先编译
email_pattern = re.compile(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}’)

def find_emails_optimized(text):
return email_pattern.findall(text)

# 测试性能
import time

large_text = “contact us: support@example.com, sales@example.org ” * 10000

# 方法1
start = time.time()
for _ in range(100):
find_emails(large_text)
time1 = time.time() – start

# 方法2
start = time.time()
for _ in range(100):
find_emails_optimized(large_text)
time2 = time.time() – start

print(f”未编译耗时: {time1:.4f}秒”)
print(f”编译后耗时: {time2:.4f}秒”)
print(f”性能提升: {time1/time2:.2f}倍”)
输出
:
未编译耗时: 0.8567秒
编译后耗时: 0.2341秒
性能提升: 3.66倍
5.2 使用原始字符串
在Python中,建议使用原始字符串(raw string)来写正则表达式,避免转义字符的困扰。
import re

# 不推荐:需要双反斜杠
pattern1 = “\\d+\\.\\d+”

# 推荐:使用原始字符串
pattern2 = r”\d+\.\d+”

text = “3.14159”
print(re.findall(pattern1, text)) # [‘3.14159’]
print(re.findall(pattern2, text)) # [‘3.14159’]
5.3 避免过度复杂的正则表达式
过于复杂的正则表达式难以维护且容易出错。如果表达式过于复杂,考虑拆分为多个步骤或使用字符串方法。
import re

# 复杂的正则表达式(不推荐)
# 匹配复杂日期格式:YYYY-MM-DD 或 YYYY/MM/DD 或 YYYY年MM月DD日
complex_pattern = r”(\d{4}[-/]\d{1,2}[-/]\d{1,2})|(\d{4}年\d{1,2}月\d{1,2}日)”

# 拆分为多个步骤(推荐)
def extract_dates(text):
dates = []
# 先匹配第一种格式
dates.extend(re.findall(r”\d{4}[-/]\d{1,2}[-/]\d{1,2}”, text))
# 再匹配第二种格式
dates.extend(re.findall(r”\d{4}年\d{1,2}月\d{1,2}日”, text))
return dates

text = “日期1: 2024-01-15, 日期2: 2024/01/15, 日期3: 2024年01月15日”
print(extract_dates(text)) # [‘2024-01-15’, ‘2024/01/15’, ‘2024年01月15日’]
5.4 处理Unicode字符
在处理多语言文本时,需要注意Unicode字符的匹配。
import re

# 匹配中文
chinese_pattern = r”[\u4e00-\u9fff]+”
text = “Hello 世界 123″
print(re.findall(chinese_pattern, text)) # [‘世界’]

# 匹配所有字母(包括非ASCII字母)
# 使用re.UNICODE标志(Python 3中默认启用)
letter_pattern = r”\w+”
text = “Hello 世界 123”
print(re.findall(letter_pattern, text)) # [‘Hello’, ‘世界’, ‘123’]
5.5 使用flags参数
re
模块提供了一些flags参数,可以改变正则表达式的行为。
import re

text = “Hello World\nThis is Python”

# re.IGNORECASE (re.I):忽略大小写
print(re.findall(r”hello”, text, re.I)) # [‘Hello’]

# re.MULTILINE (re.M):多行模式,^和$匹配每行的开头和结尾
print(re.findall(r”^This”, text, re.M)) # [‘This’]

# re.DOTALL (re.S):让点号.匹配包括换行符在内的所有字符
print(re.findall(r”World.*Python”, text, re.S)) # [‘World\nThis is Python’]

# re.VERBOSE (re.X):允许正则表达式中添加注释和空格,提高可读性
pattern = re.compile(r”””
\d{3,4} # 匹配3或4位数字
-? # 可选的连字符
\d{4} # 匹配4位数字
“””, re.VERBOSE)
print(pattern.findall(“123-4567, 12345678”)) # [‘123-4567’, ‘12345678’]
5.6 处理匹配失败
在实际应用中,需要妥善处理匹配失败的情况。
import re

def safe_extract(pattern, text, default=None):
“””
安全地提取匹配内容
:param pattern: 正则表达式模式
:param text: 文本
:param default: 匹配失败时的默认值
:return: 匹配结果或默认值
“””
try:
match = re.search(pattern, text)
if match:
return match.group(1) if match.groups() else match.group()
return default
except re.error as e:
print(f”正则表达式错误: {e}”)
return default

# 示例
text = “订单号: 20240115001″
result = safe_extract(r”订单号: (\d+)”, text)
print(“提取结果:”, result) # 20240115001

# 处理匹配失败
result = safe_extract(r”订单号: (\d+)”, “无订单信息”)
print(“匹配失败:”, result) # None
6. 调试与测试正则表达式
6.1 在线工具
使用在线正则表达式测试工具可以帮助快速验证和调试:
Regex101
:
https://regex101.com/
(支持Python语法)
RegExr
:
https://regexr.com/
Debuggex
:
https://www.debuggex.com/
(可视化正则表达式)
6.2 Python调试技巧
import re

def debug_regex(pattern, text):
“””
调试正则表达式
“””
print(f”模式: {pattern}”)
print(f”文本: {text}”)

try:
# 显示匹配过程
match = re.search(pattern, text)
if match:
print(f”匹配成功: {match.group()}”)
print(f”匹配位置: {match.start()}-{match.end()}”)
if match.groups():
print(f”捕获组: {match.groups()}”)
else:
print(“匹配失败”)
except re.error as e:
print(f”语法错误: {e}”)

# 示例
debug_regex(r”\d+”, “abc123def”)
debug_regex(r”\d+”, “abcdef”)
debug_regex(r”\d+”, “abc”)
6.3 单元测试
为正则表达式编写单元测试,确保其正确性。
import re
import unittest

class TestRegex(unittest.TestCase):
def setUp(self):
self.email_pattern = re.compile(r’^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$’)

def test_valid_emails(self):
valid_emails = [“user@example.com”, “user.name+tag@example.co.uk”]
for email in valid_emails:
self.assertTrue(self.email_pattern.match(email))

def test_invalid_emails(self):
invalid_emails = [“invalid@”, “@example.com”, “user@.com”]
for email in invalid_emails:
self.assertFalse(self.email_pattern.match(email))

if __name__ == ‘__main__’:
unittest.main()
7. 总结
正则表达式是Python中处理文本的利器,掌握它能够极大地提高数据处理的效率。从基础的字符串匹配到复杂的数据清洗,正则表达式都有其用武之地。然而,正则表达式的学习需要时间和实践,建议从简单模式开始,逐步掌握高级技巧。
在实际应用中,记住以下几点:
先简单后复杂
:从最简单的模式开始,逐步增加复杂度
测试驱动
:使用在线工具或编写测试用例验证正则表达式
性能考虑
:编译常用模式,避免过度复杂的表达式
可读性
:使用原始字符串和注释(re.VERBOSE)提高可读性
备选方案
:对于复杂HTML/XML解析,考虑使用专门的解析库
通过本指南的学习和实践,相信你已经对Python正则表达式有了全面的了解。接下来,尝试在你的项目中应用这些知识,解决实际的字符串处理问题吧!
# Python正则表达式实战指南 从字符串匹配到数据清洗的常见问题与解决方案
正则表达式(Regular Expression,简称 regex 或 regexp)是Python中处理字符串的强大工具,它使用一种特殊的语法规则来描述和匹配字符串的模式。在数据清洗、文本处理、日志分析等场景中,正则表达式扮演着不可或缺的角色。然而,正则表达式的学习曲线较为陡峭,语法复杂且容易出错。本指南将从基础到进阶,通过实战案例详细讲解Python正则表达式的使用方法,帮助你解决从字符串匹配到数据清洗的常见问题。
1. Python正则表达式基础
在使用Python正则表达式之前,首先需要了解Python内置的
re
模块。该模块提供了正则表达式操作的所有核心功能。
1.1 常用函数介绍
re.match()
: 从字符串的起始位置匹配一个模式,如果起始位置匹配成功,则返回匹配对象,否则返回None。
re.search()
: 扫描整个字符串并返回第一个成功的匹配。
re.findall()
: 查找字符串中所有匹配的子串,并以列表形式返回。
re.finditer()
: 查找字符串中所有匹配的子串,并返回一个迭代器,每个迭代元素都是一个匹配对象。
re.sub()
: 替换字符串中所有匹配的子串。
1.2 基础示例
import re

text = “Python is a great programming language. Python is easy to learn.”

# match: 从开头匹配
match_result = re.match(r”Python”, text)
print(“match结果:”, match_result.group() if match_result else “None”)

# search: 搜索第一个匹配
search_result = re.search(r”Python”, text)
print(“search结果:”, search_result.group() if search_result else “None”)

# findall: 查找所有匹配
findall_result = re.findall(r”Python”, text)
print(“findall结果:”, findall_result)

# finditer: 查找所有匹配并返回迭代器
finditer_result = re.finditer(r”Python”, text)
for match in finditer_result:
print(“finditer结果:”, match.group(), “位置:”, match.start())

# sub: 替换
sub_result = re.sub(r”Python”, “Java”, text)
print(“sub结果:”, sub_result)
输出结果
:
match结果: Python
search结果: Python
findall结果: [‘Python’, ‘Python’]
finditer结果: Python 位置: 0
finditer结果: Python 位置: 30
sub结果: Java is a great programming language. Java is easy to learn.
注意
:
re.match()
只从字符串开头匹配,如果开头不匹配,即使后面有匹配的内容也会返回None。
re.search()
会扫描整个字符串,但只返回第一个匹配。
re.findall()
返回所有匹配的子串列表,如果正则表达式中有分组,则返回分组元组的列表。
re.finditer()
返回匹配对象的迭代器,可以获取匹配的位置等详细信息。
re.sub()
用于替换匹配的子串,第一个参数是模式,第二个是替换内容,第三个是原字符串。
2. 正则表达式语法规则
正则表达式的语法由普通字符(如字母、数字)和特殊字符(元字符)组成。下面介绍常用的语法规则。
2.1 元字符
元字符
描述
示例
.
匹配除换行符外的任意字符
a.c
匹配 “abc”, “aac”, “a c”
^
匹配字符串的开头
^Hello
匹配以 “Hello” 开头的字符串
$
匹配字符串的结尾
world$
匹配以 “world” 结尾的字符串
*
匹配前一个字符0次或多次
ab*c
匹配 “ac”, “abc”, “abbc”
+
匹配前一个字符1次或多次
ab+c
匹配 “abc”, “abbc”
?
匹配前一个字符0次或1次
ab?c
匹配 “ac”, “abc”
{n}
匹配前一个字符n次
a{3}c
匹配 “aaac”
{n,}
匹配前一个字符至少n次
a{3,}c
匹配 “aaac”, “aaaac”
{n,m}
匹配前一个字符n到m次
a{3,5}c
匹配 “aaac”, “aaaac”, “aaaaac”
[]
匹配括号内的任意一个字符
[abc]
匹配 “a”, “b”, “c”
[^]
匹配不在括号内的任意一个字符
[^abc]
匹配除a,b,c外的字符
|
或运算符
a|b
匹配 “a” 或 “b”
()
分组,捕获内容
(abc)+
匹配 “abc”, “abcabc”
2.2 预定义字符集
符号
描述
示例
\d
匹配任意数字,等价于
[0-9]
\d+
匹配一个或多个数字
\D
匹配任意非数字
\D+
匹配一个或多个非数字
\w
匹配字母、数字、下划线,等价于
[a-zA-Z0-9_]
\w+
匹配单词
\W
匹配非字母数字下划线
\W+
匹配非单词字符
\s
匹配任意空白字符(空格、制表符、换行符等)
\s+
匹配一个或多个空白
\S
匹配任意非空白字符
\S+
匹配非空白字符
2.3 转义字符
在正则表达式中,如果要匹配元字符本身,需要使用反斜杠
\
进行转义。例如,匹配点号
.
需要写成
\.
,匹配反斜杠
\
需要写成
\\
。
import re

text = “a.b.c”
# 匹配点号
result = re.findall(r”\.”, text)
print(“匹配点号:”, result) # 输出: [‘.’, ‘.’]

# 匹配反斜杠
text2 = “a\b\c”
# 注意:在Python字符串中,\b是退格符,所以需要写成”a\\b\\c”或使用原始字符串
text2 = r”a\b\c”
result2 = re.findall(r”\\”, text2)
print(“匹配反斜杠:”, result2) # 输出: [‘\\’, ‘\\’]
2.4 分组与捕获
使用
()
可以对模式进行分组,并捕获匹配的内容。捕获的内容可以通过匹配对象的
group()
方法获取。
import re

text = “我的电话是138-1234-5678,另一个是139-8765-4321″
pattern = r”(\d{3})-(\d{4})-(\d{4})”
matches = re.findall(pattern, text)
print(“分组捕获:”, matches) # 输出: [(‘138’, ‘1234’, ‘5678’), (‘139’, ‘8765’, ‘4321’)]

# 使用group获取匹配对象
for match in re.finditer(pattern, text):
print(“完整匹配:”, match.group(0))
print(“第一组:”, match.group(1))
print(“第二组:”, match.group(2))
print(“第三组:”, match.group(3))
2.5 非捕获分组
有时我们只需要分组的功能,但不需要捕获内容,可以使用
(?:)
语法。
import re

text = “abc123def456″
pattern = r”(?:abc|def)(\d+)”
matches = re.findall(pattern, text)
print(“非捕获分组:”, matches) # 输出: [‘123’, ‘456’],只捕获数字部分
2.6 贪婪与非贪婪
正则表达式默认是贪婪匹配,即尽可能多地匹配字符。在量词后加
?
可以变为非贪婪匹配。
import re

text = “

content

”
# 贪婪匹配
greedy = re.findall(r”<.*>“, text)
print(“贪婪匹配:”, greedy) # 输出: [‘

content

‘]

# 非贪婪匹配
non_greedy = re.findall(r”<.*?>“, text)
print(“非贪婪匹配:”, non_greedy) # 输出: [‘

‘, ‘

‘]
2.7 断言(Lookaround)
断言是零宽断言,用于查找在某些内容之前或之后的内容,但不包含这些内容本身。
零宽正向先行断言
(?=…)
: 匹配后面是…的内容
零宽负向先行断言
(?!…)
: 匹配后面不是…的内容
零宽正向后行断言
(?<=...) : 匹配前面是…的内容 零宽负向后行断言 (? {normalize_date(date)}”)
输出
:
2024/01/15 -> 2024-01-15
01-15-2024 -> 2024-01-15
2024年01月15日 -> 2024-01-15
2024/1/5 -> 2024-01-05
4.3 案例3:提取HTML中的文本内容
问题
: 需要从HTML字符串中提取纯文本内容,去除所有标签。
解决方案
: 使用正则表达式替换HTML标签。
import re

html = “””

标题

这是段落内容,包含强调文本。

链接

“””

# 去除所有HTML标签
text = re.sub(r’<[^>]+>’, ”, html)
print(“提取的文本:”, text.strip())
输出
:
提取的文本: 标题
这是段落内容,包含强调文本。
链接
注意
: 对于复杂的HTML解析,建议使用专门的库如BeautifulSoup,因为正则表达式可能无法处理嵌套标签或特殊情况。
4.4 案例4:清理用户输入中的特殊字符
问题
: 用户输入可能包含不需要的特殊字符、表情符号等,需要清理。
解决方案
: 使用正则表达式保留允许的字符。
import re

def clean_user_input(text, allow_chars=r’a-zA-Z0-9\s’):
“””
清理用户输入,只保留指定字符
:param text: 输入文本
:param allow_chars: 允许的字符集(正则表达式字符类)
:return: 清理后的文本
“””
# 构建正则表达式:匹配不在允许范围内的字符
pattern = f'[^{allow_chars}]’
return re.sub(pattern, ”, text)

# 示例:只保留字母、数字和空格
user_input = “Hello! @#$%^&*() 世界 123 😊”
cleaned = clean_user_input(user_input)
print(“原始输入:”, user_input)
print(“清理后:”, cleaned)

# 只保留中文、字母和数字
cleaned_cn = clean_user_input(user_input, r’a-zA-Z0-9\s\u4e00-\u9fff’)
print(“保留中文:”, cleaned_cn)
输出
:
原始输入: Hello! @#$%^&*() 世界 123 😊
清理后: Hello 世界 123
保留中文: Hello 世界 123
解释
:
[^…]
:匹配不在括号内的字符
\u4e00-\u9fff
:Unicode范围,匹配中文字符
表情符号😊被移除,因为它不在允许的字符范围内
4.5 案例5:批量替换文本中的占位符
问题
: 模板文本中包含多个占位符如
{name}
、
{email}
,需要根据字典替换为实际值。
解决方案
: 使用
re.sub()
配合函数进行替换。
import re

def replace_placeholders(template, data):
“””
替换模板中的占位符
:param template: 模板字符串,如”Hello {name}, your email is {email}”
:param data: 字典,包含占位符对应的值
:return: 替换后的字符串
“””
def replacer(match):
key = match.group(1)
return data.get(key, match.group(0))

pattern = r’\{(\w+)\}’
return re.sub(pattern, replacer, template)

# 示例
template = “尊敬的{username},您的订单{order_id}已发货,预计{date}送达。”
data = {
“username”: “张三”,
“order_id”: “20240115001”,
“date”: “2024-01-20”
}

result = replace_placeholders(template, data)
print(“模板:”, template)
print(“替换后:”, result)
输出
:
模板: 尊敬的{username},您的订单{order_id}已发货,预计{date}送达。
替换后: 尊敬的张三,您的订单20240115001已发货,预计2024-01-20送达。
解释
:
r’\{(\w+)\}’
:匹配
{占位符}
格式,
\w+
匹配字母数字下划线,
()
捕获占位符名称
replacer
函数:根据捕获的占位符名称从字典中获取值进行替换
re.sub()
:对每个匹配调用
replacer
函数
5. 性能优化与最佳实践
5.1 编译正则表达式
如果同一个正则表达式需要多次使用,应该先编译,以提高性能。
import re

# 不推荐:每次调用都重新编译
def find_emails(text):
return re.findall(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}’, text)

# 推荐:预先编译
email_pattern = re.compile(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}’)

def find_emails_optimized(text):
return email_pattern.findall(text)

# 测试性能
import time

large_text = “contact us: support@example.com, sales@example.org ” * 10000

# 方法1
start = time.time()
for _ in range(100):
find_emails(large_text)
time1 = time.time() – start

# 方法2
start = time.time()
for _ in range(100):
find_emails_optimized(large_text)
time2 = time.time() – start

print(f”未编译耗时: {time1:.4f}秒”)
print(f”编译后耗时: {time2:.4f}秒”)
print(f”性能提升: {time1/time2:.2f}倍”)
输出
:
未编译耗时: 0.8567秒
编译后耗时: 0.2341秒
性能提升: 3.66倍
5.2 使用原始字符串
在Python中,建议使用原始字符串(raw string)来写正则表达式,避免转义字符的困扰。
import re

# 不推荐:需要双反斜杠
pattern1 = “\\d+\\.\\d+”

# 推荐:使用原始字符串
pattern2 = r”\d+\.\d+”

text = “3.14159”
print(re.findall(pattern1, text)) # [‘3.14159’]
print(re.findall(pattern2, text)) # [‘3.14159’]
5.3 避免过度复杂的正则表达式
过于复杂的正则表达式难以维护且容易出错。如果表达式过于复杂,考虑拆分为多个步骤或使用字符串方法。
import re

# 复杂的正则表达式(不推荐)
# 匹配复杂日期格式:YYYY-MM-DD 或 YYYY/MM/DD 或 YYYY年MM月DD日
complex_pattern = r”(\d{4}[-/]\d{1,2}[-/]\d{1,2})|(\d{4}年\d{1,2}月\d{1,2}日)”

# 拆分为多个步骤(推荐)
def extract_dates(text):
dates = []
# 先匹配第一种格式
dates.extend(re.findall(r”\d{4}[-/]\d{1,2}[-/]\d{1,2}”, text))
# 再匹配第二种格式
dates.extend(re.findall(r”\d{4}年\d{1,2}月\d{1,2}日”, text))
return dates

text = “日期1: 2024-01-15, 日期2: 2024/01/15, 日期3: 2024年01月15日”
print(extract_dates(text)) # [‘2024-01-15’, ‘2024/01/15’, ‘2024年01月15日’]
5.4 处理Unicode字符
在处理多语言文本时,需要注意Unicode字符的匹配。
import re

# 匹配中文
chinese_pattern = r”[\u4e00-\u9fff]+”
text = “Hello 世界 123″
print(re.findall(chinese_pattern, text)) # [‘世界’]

# 匹配所有字母(包括非ASCII字母)
# 使用re.UNICODE标志(Python 3中默认启用)
letter_pattern = r”\w+”
text = “Hello 世界 123”
print(re.findall(letter_pattern, text)) # [‘Hello’, ‘世界’, ‘123’]
5.5 使用flags参数
re
模块提供了一些flags参数,可以改变正则表达式的行为。
import re

text = “Hello World\nThis is Python”

# re.IGNORECASE (re.I):忽略大小写
print(re.findall(r”hello”, text, re.I)) # [‘Hello’]

# re.MULTILINE (re.M):多行模式,^和$匹配每行的开头和结尾
print(re.findall(r”^This”, text, re.M)) # [‘This’]

# re.DOTALL (re.S):让点号.匹配包括换行符在内的所有字符
print(re.findall(r”World.*Python”, text, re.S)) # [‘World\nThis is Python’]

# re.VERBOSE (re.X):允许正则表达式中添加注释和空格,提高可读性
pattern = re.compile(r”””
\d{3,4} # 匹配3或4位数字
-? # 可选的连字符
\d{4} # 匹配4位数字
“””, re.VERBOSE)
print(pattern.findall(“123-4567, 12345678”)) # [‘123-4567’, ‘12345678’]
5.6 处理匹配失败
在实际应用中,需要妥善处理匹配失败的情况。
import re

def safe_extract(pattern, text, default=None):
“””
安全地提取匹配内容
:param pattern: 正则表达式模式
:param text: 文本
:param default: 匹配失败时的默认值
:return: 匹配结果或默认值
“””
try:
match = re.search(pattern, text)
if match:
return match.group(1) if match.groups() else match.group()
return default
except re.error as e:
print(f”正则表达式错误: {e}”)
return default

# 示例
text = “订单号: 20240115001″
result = safe_extract(r”订单号: (\d+)”, text)
print(“提取结果:”, result) # 20240115001

# 处理匹配失败
result = safe_extract(r”订单号: (\d+)”, “无订单信息”)
print(“匹配失败:”, result) # None
6. 调试与测试正则表达式
6.1 在线工具
使用在线正则表达式测试工具可以帮助快速验证和调试:
Regex101
:
https://regex101.com/
(支持Python语法)
RegExr
:
https://regexr.com/
Debuggex
:
https://www.debuggex.com/
(可视化正则表达式)
6.2 Python调试技巧
import re

def debug_regex(pattern, text):
“””
调试正则表达式
“””
print(f”模式: {pattern}”)
print(f”文本: {text}”)

try:
# 显示匹配过程
match = re.search(pattern, text)
if match:
print(f”匹配成功: {match.group()}”)
print(f”匹配位置: {match.start()}-{match.end()}”)
if match.groups():
print(f”捕获组: {match.groups()}”)
else:
print(“匹配失败”)
except re.error as e:
print(f”语法错误: {e}”)

# 示例
debug_regex(r”\d+”, “abc123def”)
debug_regex(r”\d+”, “abcdef”)
debug_regex(r”\d+”, “abc”)
6.3 单元测试
为正则表达式编写单元测试,确保其正确性。
import re
import unittest

class TestRegex(unittest.TestCase):
def setUp(self):
self.email_pattern = re.compile(r’^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$’)

def test_valid_emails(self):
valid_emails = [“user@example.com”, “user.name+tag@example.co.uk”]
for email in valid_emails:
self.assertTrue(self.email_pattern.match(email))

def test_invalid_emails(self):
invalid_emails = [“invalid@”, “@example.com”, “user@.com”]
for email in invalid_emails:
self.assertFalse(self.email_pattern.match(email))

if __name__ == ‘__main__’:
unittest.main()
7. 总结
正则表达式是Python中处理文本的利器,掌握它能够极大地提高数据处理的效率。从基础的字符串匹配到复杂的数据清洗,正则表达式都有其用武之地。然而,正则表达式的学习需要时间和实践,建议从简单模式开始,逐步掌握高级技巧。
在实际应用中,记住以下几点:
先简单后复杂
:从最简单的模式开始,逐步增加复杂度
测试驱动
:使用在线工具或编写测试用例验证正则表达式
性能考虑
:编译常用模式,避免过度复杂的表达式
可读性
:使用原始字符串和注释(re.VERBOSE)提高可读性
备选方案
:对于复杂HTML/XML解析,考虑使用专门的解析库
通过本指南的学习和实践,相信你已经对Python正则表达式有了全面的了解。接下来,尝试在你的项目中应用这些知识,解决实际的字符串处理问题吧!