正则表达式(Regular Expressions,简称 regex)是一种强大的文本处理工具,用于匹配字符串中的字符组合。Python 提供了 re 模块来支持正则表达式的操作。以下是一些常用的正则表达式操作和示例:
导入 re 模块
首先,你需要导入 re 模块:
python复制代码
|---|-------------|
| | import re |
基本用法
1. 匹配字符串
使用 re.match() 函数从字符串的起始位置匹配正则表达式:
python复制代码
|---|---------------------------------------|
| | pattern = r'\d+' # 匹配一个或多个数字 |
| | match = re.match(pattern, '123abc') |
| | if match: |
| | print(match.group()) # 输出: 123 |
2. 搜索字符串
使用 re.search() 函数在字符串中搜索正则表达式(返回第一个匹配):
python复制代码
|---|----------------------------------------|
| | pattern = r'\d+' |
| | match = re.search(pattern, 'abc123') |
| | if match: |
| | print(match.group()) # 输出: 123 |
3. 查找所有匹配项
使用 re.findall() 函数查找字符串中所有匹配正则表达式的子串:
python复制代码
|---|-------------------------------------------------|
| | pattern = r'\d+' |
| | matches = re.findall(pattern, 'abc123def456') |
| | print(matches) # 输出: ['123', '456'] |
4. 替换字符串
使用 re.sub() 函数替换字符串中匹配正则表达式的部分:
python复制代码
|---|------------------------------------------------------|
| | pattern = r'\d+' |
| | result = re.sub(pattern, 'number', 'abc123def456') |
| | print(result) # 输出: abcnumberdefnumber |
常用正则表达式符号
.:匹配除换行符以外的任意字符。^:匹配字符串的开始。$:匹配字符串的结束。*:匹配前面的字符零次或多次。+:匹配前面的字符一次或多次。?:匹配前面的字符零次或一次。{n}:匹配前面的字符恰好 n 次。{n,}:匹配前面的字符至少 n 次。{n,m}:匹配前面的字符至少 n 次,但不超过 m 次。[]:字符集,匹配括号中的任意一个字符。|:逻辑或,匹配左右两边的任意一个表达式。():分组,用于提取匹配的子串。\\:转义字符,用于匹配特殊字符(如.、*、?等)。
示例
匹配电子邮件地址
python复制代码
|---|---------------------------------------------------------------|
| | pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' |
| | match = re.match(pattern, 'example@example.com') |
| | if match: |
| | print("Valid email address") |
| | else: |
| | print("Invalid email address") |
匹配 URL
python复制代码
|---|------------------------------------------------------------------------------|
| | pattern = r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+' |
| | match = re.search(pattern, 'Visit https://www.example.com for more info.') |
| | if match: |
| | print("Found a URL:", match.group()) |
编译正则表达式
为了提高效率,你可以使用 re.compile() 函数编译正则表达式,然后多次使用编译后的模式:
python复制代码
|---|---------------------------------------------|
| | pattern = re.compile(r'\d+') |
| | matches = pattern.findall('abc123def456') |
| | print(matches) # 输出: ['123', '456'] |
捕获组
使用括号 () 可以捕获匹配的子串:
python复制代码
|---|--------------------------------------------|
| | pattern = r'(\d+)-(\d+)-(\d+)' |
| | match = re.match(pattern, '2023-10-05') |
| | if match: |
| | year, month, day = match.groups() |
| | print(year, month, day) # 输出: 2023 10 05 |
命名捕获组
你可以给捕获组命名,以便更容易地访问它们:
python复制代码
|---|-----------------------------------------------------------------------------------------|
| | pattern = r'(?P<year>\d+)-(?P<month>\d+)-(?P<day>\d+)' |
| | match = re.match(pattern, '2023-10-05') |
| | if match: |
| | print(match.group('year'), match.group('month'), match.group('day')) # 输出: 2023 10 05 |
正则表达式是一个非常强大的工具,适用于各种文本处理任务。通过掌握基本的正则表达式语法和 Python 的 re 模块,你可以高效地处理和分析字符串数据。