Python 使用正则表达式截取字符串
在 Python 中,可以使用 re 模块结合正则表达式来灵活地截取字符串,以下是几种常见的用法:

使用 re.findall() 提取所有匹配项
import re
text = "电话:13812345678,邮箱:test@example.com,电话:13987654321"
# 提取所有电话号码
phones = re.findall(r'1[3-9]\d{9}', text)
print(phones) # 输出: ['13812345678', '13987654321']
# 提取所有邮箱
emails = re.findall(r'[\w\.-]+@[\w\.-]+\.\w+', text)
print(emails) # 输出: ['test@example.com']
使用 re.search() 提取第一个匹配项
import re
text = "订单号:ORD2025001,金额:¥199.50"
# 提取订单号
match = re.search(r'订单号:(\w+)', text)
if match:
order_id = match.group(1)
print(order_id) # 输出: ORD2025001
# 提取金额
match = re.search(r'金额:¥(\d+\.\d{2})', text)
if match:
amount = match.group(1)
print(amount) # 输出: 199.50
使用 re.match() 从字符串开头匹配
import re
text = "2025-01-15 订单信息"
# 匹配日期
match = re.match(r'(\d{4}-\d{2}-\d{2})', text)
if match:
date = match.group(1)
print(date) # 输出: 2025-01-15
使用 re.split() 分割字符串
import re text = "apple,orange;banana|grape" # 使用多种分隔符分割 fruits = re.split(r'[;,|]', text) print(fruits) # 输出: ['apple', 'orange', 'banana', 'grape']
使用 re.sub() 替换字符串
import re
text = "我的电话是13812345678,请勿拨打13812345678"
# 替换电话号码为隐藏
masked_text = re.sub(r'1[3-9]\d{9}', '***', text)
print(masked_text) # 输出: 我的电话是***,请勿拨打***
使用正则表达式捕获组
import re
text = "姓名:张三,年龄:25,职业:工程师"
# 提取多个信息
pattern = r'姓名:(\w+),年龄:(\d+),职业:(\w+)'
match = re.search(pattern, text)
if match:
name, age, job = match.groups()
print(f"姓名: {name}, 年龄: {age}, 职业: {job}")
# 输出: 姓名: 张三, 年龄: 25, 职业: 工程师
使用命名捕获组
import re
text = "订单号:ORD2025001,金额:¥199.50"
pattern = r'订单号:(?P<order>\w+),金额:¥(?P<amount>\d+\.\d{2})'
match = re.search(pattern, text)
if match:
print(match.group('order')) # 输出: ORD2025001
print(match.group('amount')) # 输出: 199.50
常用正则表达式示例
| 用途 | 正则表达式 | 示例 |
|---|---|---|
| 手机号码 | 1[3-9]\d{9} |
13812345678 |
| 邮箱 | [\w\.-]+@[\w\.-]+\.\w+ |
user@example.com |
| 日期 | \d{4}-\d{2}-\d{2} |
2025-01-15 |
| IP地址 | \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} |
168.1.1 |
| 中文字符 | [\u4e00-\u9fa5]+ |
你好 |
| URL | https?://[^\s]+ |
https://www.example.com |
注意事项
- 正则表达式中的特殊字符需要转义,如 、、、、
^、、、、[、]、\、、、 - 使用
re.escape()可以自动转义字符串中的特殊字符 - 对于复杂的正则表达式,可以使用
re.VERBOSE模式添加注释 - 考虑性能问题,对于大量文本处理,预编译正则表达式会更高效:
import re
# 预编译正则表达式
phone_pattern = re.compile(r'1[3-9]\d{9}')
text = "电话:13812345678"
match = phone_pattern.search(text)
if match:
print(match.group()) # 输出: 13812345678
希望这些示例能帮助你更好地使用正则表达式截取字符串!

