您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python中怎么利用正则抓取数据
正则表达式(Regular Expression)是处理字符串的强大工具,Python通过内置的`re`模块提供了完整的正则支持。本文将详细介绍如何利用Python正则表达式高效抓取结构化数据。
## 一、正则表达式基础
### 1. 基本元字符
- `.` 匹配任意字符(除换行符)
- `\d` 匹配数字 → 等价于[0-9]
- `\w` 匹配字母数字下划线 → 等价于[A-Za-z0-9_]
- `\s` 匹配空白字符(空格、制表符等)
- `^` 匹配字符串开头
- `$` 匹配字符串结尾
### 2. 量词符号
- `*` 0次或多次
- `+` 1次或多次
- `?` 0次或1次
- `{n}` 精确n次
- `{n,}` 至少n次
- `{n,m}` n到m次
## 二、Python re模块核心方法
### 1. re.match()
从字符串起始位置匹配模式:
```python
import re
result = re.match(r'\d+', '123abc')
if result:
print(result.group()) # 输出: 123
扫描整个字符串返回第一个匹配:
result = re.search(r'\d+', 'abc123def')
print(result.group()) # 输出: 123
返回所有匹配结果的列表:
results = re.findall(r'\d+', 'a1b22c333')
print(results) # 输出: ['1', '22', '333']
返回匹配结果的迭代器(适合大文本):
for match in re.finditer(r'\d+', 'a1b22c333'):
print(match.group(), match.span())
import re
html = '<a href="https://example.com">Link1</a><a href="/about">Link2</a>'
pattern = r'href=["\'](https?://[^"\']+|/[^"\']*)["\']'
urls = re.findall(pattern, html)
print(urls) # 输出: ['https://example.com', '/about']
text = "联系邮箱:service@domain.com,备用邮箱:backup@domain.org"
emails = re.findall(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', text)
print(emails) # 输出: ['service@domain.com', 'backup@domain.org']
text = "商品A价格¥299.00,商品B特价$45.99"
prices = re.findall(r'[¥$]\d+\.?\d*', text)
print(prices) # 输出: ['¥299.00', '$45.99']
默认量词是贪婪模式,添加?
转为非贪婪:
html = '<div>内容1</div><div>内容2</div>'
re.findall(r'<div>(.*?)</div>', html) # 输出: ['内容1', '内容2']
使用()
提取特定部分:
log = "[2023-08-01] ERROR: File not found"
match = re.search(r'\[(.*?)\] (ERROR|WARN): (.*)', log)
print(match.groups()) # 输出: ('2023-08-01', 'ERROR', 'File not found')
重复使用时应预编译:
pattern = re.compile(r'\d{4}-\d{2}-\d{2}')
dates = pattern.findall('日期:2023-08-01,2023-08-02')
使用re.DOTALL
或re.S
标志:
text = """<div>
多行内容
</div>"""
re.findall(r'<div>(.*)</div>', text, re.DOTALL)
使用re.IGNORECASE
或re.I
:
re.findall(r'python', 'Python PYTHON', re.I) # 输出: ['Python', 'PYTHON']
使用\u
或re.UNICODE
:
re.findall(r'[\u4e00-\u9fa5]+', '中文English混合') # 输出: ['中文']
.
(如\d
代替[0-9]
)(.*)*
re.finditer()
处理大文本注意:对于复杂HTML解析,建议结合BeautifulSoup等专业库使用,正则更适合处理有固定模式的文本数据。
通过掌握这些技巧,你可以高效地从各种文本数据中提取所需信息。正则表达式需要实践积累,建议保存常用模式片段作为自己的”正则库”。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。