Python re正则的使用
Python 中的 re
模块用于处理正则表达式,提供了多种方法来搜索、匹配和替换字符串。以下是一些常用方法的示例:
1. 导入 re
模块
import re
2. 匹配字符串
re.match()
: 从字符串的开头开始匹配。
result = re.match(r'\d+', '123abc')
if result:
print("Match:", result.group()) # 输出: Match: 123
3. 搜索字符串
re.search()
: 在整个字符串中搜索匹配。
result = re.search(r'\d+', 'abc123xyz')
if result:
print("Search:", result.group()) # 输出: Search: 123
4. 查找所有匹配
re.findall()
: 返回所有匹配的列表。
matches = re.findall(r'\d+', 'abc123xyz456')
print("Find all:", matches) # 输出: Find all: ['123', '456']
5. 替换字符串
re.sub()
: 替换字符串中的匹配项。
result = re.sub(r'\d+', 'number', 'abc123xyz')
print("Substituted:", result) # 输出: Substituted: abcnumberxyz
6. 使用分组
- 分组: 使用小括号
()
来捕获匹配的部分。
result = re.search(r'(\d+)', 'abc123xyz')
if result:
print("Captured group:", result.group(1)) # 输出: Captured group: 123
7. 使用特殊字符
.
: 匹配任何字符^
: 匹配字符串的开头$
: 匹配字符串的结尾*
: 匹配前面的字符零次或多次+
: 匹配前面的字符一次或多次?
: 匹配前面的字符零次或一次{n}
: 精确匹配 n 次
示例
以下是一个综合示例,展示了上述用法:
import re
text = "The price is 50 dollars, and there are 3 apples."
# 查找所有数字
numbers = re.findall(r'\d+', text)
print("Numbers found:", numbers) # 输出: ['50', '3']
# 替换所有数字
new_text = re.sub(r'\d+', 'X', text)
print("Text after substitution:", new_text) # 输出: The price is X dollars, and there are X apples.
小结
re
模块是处理字符串匹配和替换的强大工具,理解其基本用法将帮助你在数据处理中更加高效。你可以根据需求调整正则表达式的模式来匹配特定的字符串。