python 正则查找
时间: 2023-11-22 12:50:08 浏览: 41
以下是Python中使用正则表达式进行查找的方法和示例:
1. 导入re模块
```python
import re
```
2. 使用re.search()方法查找第一个匹配的字符串
```python
str = 'an example word:cat!!'
match = re.search(r'word:\w\w\w', str)
if match:
print('found', match.group())
else:
print('did not find')
```
输出结果为:
```
found word:cat
```
3. 使用re.findall()方法查找所有匹配的字符串
```python
str = 'purple alice-b@google.com monkey dishwasher'
emails = re.findall(r'\b\w+@\w+\.\w{2,3}\b', str)
print(emails)
```
输出结果为:
```
['b@google.com']
```
4. 使用re.finditer()方法查找所有匹配的字符串,并返回一个迭代器
```python
str = 'purple alice-b@google.com monkey dishwasher'
iterator = re.finditer(r'\b\w+@\w+\.\w{2,3}\b', str)
for match in iterator:
print(match.group())
```
输出结果为:
```
b@google.com
```