您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python中怎么利用正则表达式提取文本
正则表达式(Regular Expression)是处理文本数据的强大工具,Python通过内置的`re`模块提供了完整的正则表达式支持。本文将介绍如何利用`re`模块从文本中提取目标内容。
## 一、基础方法
### 1. re.findall() 提取所有匹配
```python
import re
text = "订单号:12345, 金额:¥200; 订单号:67890, 金额:¥500"
order_ids = re.findall(r"订单号:(\d+)", text) # 提取所有订单号
print(order_ids) # 输出: ['12345', '67890']
result = re.search(r"金额:¥(\d+)", text)
if result:
print(result.group(1)) # 输出: 200
pattern = r"订单号:(?P<id>\d+).*?金额:¥(?P<amount>\d+)"
match = re.search(pattern, text)
if match:
print(match.group('id')) # 输出: 12345
print(match.group('amount')) # 输出: 200
multi_text = """姓名: 张三
电话: 13800138000
地址: 北京市"""
phone = re.search(r"电话:\s*(\d+)", multi_text).group(1)
print(phone) # 输出: 13800138000
html = '<a href="https://example.com">链接</a>'
urls = re.findall(r'href="(https?://[^"]+)"', html)
print(urls) # 输出: ['https://example.com']
log = "[2023-08-15 14:30:22] 用户登录成功"
timestamp = re.search(r"\[(.*?)\]", log).group(1)
print(timestamp) # 输出: 2023-08-15 14:30:22
pattern = r"""
(?P<year>\d{4})- # 年
(?P<month>\d{2})- # 月
(?P<day>\d{2}) # 日
"""
特殊字符需要转义,如\.
表示真实的点号
性能考虑:对大量文本建议预编译正则
compiled_re = re.compile(r'\d+')
通过合理使用正则表达式,可以高效完成各种文本提取任务。建议结合在线正则测试工具(如regex101)进行调试。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。