Skip to content

第七章 正则表达式 v1.0 ​

Python标准库中的re模块提供了正则表达式的支持,用于字符串匹配和处理

1.re模块 ​

Python标准库中的正则表达式模块,用于查找相关标准文本模式

正则表达式字符分类与符号作用
字符描述
\d0~9中任意数字
\D除0~9之外任何字符
\w任何字母、数字或下划线字符
\W除字母、数字与下划线外的其他字符
\s空格、制表符或换行符
\S除空格、制表符或换行符外的其他字符
|称为“管道”,表示可以匹配许多表达式中的一个
.除换行符之外的所有字符
[abc]匹配方括号里的所有字符
[^abc]匹配不在方括号里的所有字符
?/*/+匹配 零次或一次/零次或多次/一次或多次 前面的分组
{n,m}匹配n~m次前面的分组(n默认为0,m默认为无数)
{n,m}?惰性(非贪心)匹配,表示尽可能匹配最短的字符串
^spam意味着字符串必须以spam开始
spam$意味着字符串必须以spam结束
\转义正则中有特殊含义的字符,如:. ^ $ * + ? { } [ ] \ | ( )

2.re模块常用函数 ​

python
import re

# re.match(): 从字符串起始位置匹配
result = re.match(r'\d+', '123abc')
if result:
    print(result.group())  # 输出: 123

# re.search(): 搜索整个字符串
result = re.search(r'\d+', 'abc123def')
if result:
    print(result.group())  # 输出: 123

# re.findall(): 返回所有匹配结果
results = re.findall(r'\d+', 'abc123def456')
print(results)  # 输出: ['123', '456']

# re.finditer(): 返回匹配迭代器
for match in re.finditer(r'\d+', 'abc123def456'):
    print(match.group())  # 输出: 123, 456
python
import re

# re.sub(): 替换匹配内容
text = 'Hello 123 World 456'
result = re.sub(r'\d+', 'NUM', text)
print(result)  # 输出: Hello NUM World NUM

# re.split(): 根据模式分割字符串
text = 'abc123def456ghi'
result = re.split(r'\d+', text)
print(result)  # 输出: ['abc', 'def', 'ghi']

# re.compile(): 编译正则表达式
pattern = re.compile(r'\d+')
result = pattern.findall('abc123def456')
print(result)  # 输出: ['123', '456']

3.分组与捕获 ​

python
import re

# 基本分组
text = '2024-01-15'
match = re.match(r'(\d{4})-(\d{2})-(\d{2})', text)
if match:
    print(match.group(0))  # 输出: 2024-01-15 (整个匹配)
    print(match.group(1))  # 输出: 2024
    print(match.group(2))  # 输出: 01
    print(match.group(3))  # 输出: 15

# 命名分组
match = re.match(r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})', text)
if match:
    print(match.group('year'))   # 输出: 2024
    print(match.group('month'))  # 输出: 01
    print(match.group('day'))    # 输出: 15