插件窝 干货文章 Python正则表达式完全指南:从入门到精通

Python正则表达式完全指南:从入门到精通

Python正则表达式完全指南:从入门到精通

1. 正则表达式简介

正则表达式(Regular Expression)是一种强大的文本处理工具,它使用特定模式来匹配、查找和替换字符串。在Python中,我们通过内置的re模块来使用正则表达式功能。

2. re模块基础用法

Python的re模块提供了多种正则表达式操作方法:

import re

# 匹配字符串
result = re.match(r'\d+', '123abc')

# 搜索字符串
result = re.search(r'\d+', 'abc123def')

# 查找所有匹配
results = re.findall(r'\d+', '123abc456def789')

# 替换字符串
new_str = re.sub(r'\d+', '#', '123abc456def789')

3. 常用正则表达式语法

  • \d - 匹配数字
  • \w - 匹配字母数字下划线
  • \s - 匹配空白字符
  • . - 匹配任意字符(除换行符)
  • * - 匹配前一个字符0次或多次
  • + - 匹配前一个字符1次或多次
  • ? - 匹配前一个字符0次或1次
  • {n} - 匹配前一个字符n次
  • ^ - 匹配字符串开头
  • $ - 匹配字符串结尾

4. 正则表达式高级技巧

4.1 分组匹配

pattern = r'(\d{3})-(\d{3,8})'
match = re.match(pattern, '010-12345')
if match:
    print(match.group(1))  # 010
    print(match.group(2))  # 12345

4.2 非贪婪匹配

# 贪婪匹配
print(re.match(r'^\d+', '123456').group())  # 123456

# 非贪婪匹配
print(re.match(r'^\d+?', '123456').group())  # 1

4.3 预编译正则表达式

pattern = re.compile(r'\d+')
result = pattern.findall('123abc456def789')

5. 常见问题解决方案

5.1 匹配中文

re.findall(r'[\u4e00-\u9fa5]+', '你好Python 2023')

5.2 匹配邮箱

re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', 'test@example.com')

5.3 匹配URL

re.match(r'https?://[\w\.-]+\.[\w\.-]+(/[\w\.-]*)*', 'https://www.example.com/path')

6. 性能优化建议

  1. 预编译常用正则表达式
  2. 避免过度使用.*这样的贪婪匹配
  3. 尽量使用具体字符集代替.
  4. 考虑使用字符串内置方法替代简单正则

通过掌握这些正则表达式技巧,你将能够高效处理Python中的各种文本匹配和提取任务。