re.search() 和 match 函数一样只能匹配第一个位置吗
时间: 2024-04-17 22:25:59 浏览: 28
不完全正确。虽然 `re.search()` 函数默认只匹配第一个位置,但是它可以通过 `pos` 和 `endpos` 参数来指定搜索的起始和结束位置。
下面是一个示例代码,说明如何使用 `re.search()` 函数来匹配多个位置:
```python
import re
text = "Hello, Hello, Hello!"
pattern = r"Hello"
# 使用 re.search() 函数匹配多个位置
start_pos = 0
while True:
match = re.search(pattern, text, start_pos)
if match:
start_pos = match.end()
print(f"Found at position {match.start()} - {match.end()}")
else:
break
```
在上述示例中,我们使用 `re.search()` 函数在字符串中搜索模式 "Hello" 的多个位置。通过设置 `start_pos` 变量来指定搜索的起始位置,初始值为0。
在每次循环中,我们调用 `re.search()` 函数并传入起始位置 `start_pos`,如果找到匹配位置,则打印出匹配的起始和结束位置,并将 `start_pos` 更新为当前匹配的结束位置(`match.end()`)。
然后,继续下一次循环,从上一次匹配的结束位置开始继续搜索,直到没有更多的匹配。
这样,我们就可以使用 `re.search()` 函数来匹配字符串中的多个位置,而不仅仅是第一个位置。