上一篇
Python正则表达式语法全面教程 - 从基础到高级应用
- Python
- 2025-08-14
- 1117
Python正则表达式语法完全指南
掌握文本处理的强大工具
什么是正则表达式?
正则表达式(Regular Expression)是用于匹配和处理文本的强大工具,它使用特定语法来描述字符串模式。在Python中,通过内置的re
模块提供正则表达式功能。
为什么使用正则表达式?
- 高效的文本搜索和匹配
- 复杂字符串模式的验证(如邮箱、URL等)
- 文本提取和数据处理
- 字符串替换和格式化
Python re模块基础
在Python中使用正则表达式前,需要先导入re模块:
import re
re模块提供了几个核心函数:
函数 | 描述 | 返回值 |
---|---|---|
re.match() |
从字符串开头匹配模式 | 匹配对象或None |
re.search() |
搜索整个字符串匹配模式 | 匹配对象或None |
re.findall() |
查找所有匹配的子串 | 字符串列表 |
re.finditer() |
查找所有匹配的子串 | 匹配对象迭代器 |
re.sub() |
替换匹配的子串 | 替换后的字符串 |
正则表达式基础语法
1. 普通字符
大多数字符(字母、数字)会直接匹配自身:
python
匹配字符串 "python"123
匹配字符串 "123"
2. 元字符
具有特殊含义的字符:
元字符 | 描述 | 示例 |
---|---|---|
. |
匹配除换行符外的任意字符 | a.c 匹配 "abc", "aac", "a c" 等 |
^ |
匹配字符串开头 | ^Hello 匹配以"Hello"开头的字符串 |
$ |
匹配字符串结尾 | world$ 匹配以"world"结尾的字符串 |
* |
匹配前一个字符0次或多次 | ab*c 匹配 "ac", "abc", "abbc" 等 |
+ |
匹配前一个字符1次或多次 | ab+c 匹配 "abc", "abbc" 但不匹配 "ac" |
? |
匹配前一个字符0次或1次 | ab?c 匹配 "ac" 或 "abc" |
| |
逻辑或,匹配多个模式之一 | cat|dog 匹配 "cat" 或 "dog" |
3. 字符类
使用方括号定义字符集合:
[abc]
匹配a、b或c中的任意一个字符[a-z]
匹配任意小写字母[0-9]
匹配任意数字[^abc]
匹配除a、b、c外的任意字符
4. 预定义字符类
字符类 | 等价形式 | 描述 |
---|---|---|
\d |
[0-9] |
匹配任意数字 |
\D |
[^0-9] |
匹配非数字字符 |
\s |
[ \t\n\r\f\v] |
匹配空白字符 |
\S |
[^ \t\n\r\f\v] |
匹配非空白字符 |
\w |
[a-zA-Z0-9_] |
匹配字母、数字和下划线 |
5. 量词
用于指定匹配次数:
{n}
匹配前一个字符恰好n次{n,}
匹配前一个字符至少n次{n,m}
匹配前一个字符n到m次
高级正则表达式语法
1. 分组和捕获
使用圆括号()
创建分组:
- 捕获分组:
(pattern)
- 匹配并捕获结果 - 非捕获分组:
(?:pattern)
- 匹配但不捕获
import re
text = "John: 30, Jane: 28"
pattern = r"(\w+): (\d+)"
matches = re.findall(pattern, text)
print(matches) # 输出: [('John', '30'), ('Jane', '28')]
2. 后向引用
在正则表达式中引用前面捕获的分组:
pattern = r"(\b\w+)\s+\1" # 匹配重复单词
text = "hello hello world"
match = re.search(pattern, text)
if match:
print(match.group()) # 输出: hello hello
3. 零宽断言
匹配某些位置而不消耗字符:
(?=...)
正向先行断言(?!...)
负向先行断言(?<=...)
正向后行断言(?<!...)
负向后行断言
# 匹配后面跟着.com的http
pattern = r"http(?=\.com)"
text = "http://example.com http://example.org"
matches = re.findall(pattern, text)
print(matches) # 输出: ['http'] (只匹配第一个http)
实际应用示例
1. 验证电子邮件地址
import re
def validate_email(email):
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
return re.match(pattern, email) is not None
print(validate_email("user@example.com")) # True
print(validate_email("invalid.email@")) # False
2. 提取URL中的域名
import re
text = "Visit our website at https://www.example.com or http://blog.example.org"
pattern = r"https?://(?:www\.)?([a-zA-Z0-9-]+\.[a-zA-Z]{2,})"
domains = re.findall(pattern, text)
print(domains) # 输出: ['example.com', 'example.org']
3. 清理和格式化文本
import re
text = "This text has extra spaces and punctuation!!"
cleaned = re.sub(r"\s+", " ", text) # 替换多个空格为单个空格
cleaned = re.sub(r"[^\w\s]", "", cleaned) # 移除非字母数字空格字符
print(cleaned) # 输出: "This text has extra spaces and punctuation"
最佳实践提示
- 使用原始字符串(前缀r)避免转义问题:
r"\d+"
- 复杂的正则表达式添加注释:
re.VERBOSE
标志 - 预编译常用正则表达式:
pattern = re.compile(r"...")
- 避免过度复杂的正则表达式,必要时拆分为多个步骤
- 使用在线工具(如regex101.com)测试和调试正则表达式
通过本教程,您已经掌握了Python正则表达式的基础语法和高级用法。正则表达式是处理文本数据的强大工具,多加练习将帮助您熟练掌握这一技能。
本文由ChaiZhi于2025-08-14发表在吾爱品聚,如有疑问,请联系我们。
本文链接:https://521pj.cn/20258151.html
发表评论