python search和match函数
时间: 2023-08-11 09:03:54 浏览: 56
search和match是Python中re模块提供的两个用于正则表达式匹配的函数。
search函数用于在字符串中搜索匹配正则表达式的第一个位置,并返回一个匹配对象。如果找到匹配,则返回一个Match对象,否则返回None。它的语法如下:
```python
re.search(pattern, string, flags=0)
```
其中,pattern是要匹配的正则表达式,string是要搜索的字符串,flags是可选的匹配模式参数。
例如,下面的代码使用search函数在字符串中搜索匹配的内容:
```python
import re
string = "Hello, world!"
pattern = r"\b\w{5}\b" # 匹配长度为5的单词
match = re.search(pattern, string)
if match:
print("Found:", match.group())
else:
print("Not found.")
```
输出结果为:Found: Hello
match函数与search函数类似,但它只从字符串的开头开始匹配。如果找到匹配,则返回一个Match对象,否则返回None。它的语法如下:
```python
re.match(pattern, string, flags=0)
```
同样,pattern是要匹配的正则表达式,string是要搜索的字符串,flags是可选的匹配模式参数。
下面的代码演示了match函数的使用:
```python
import re
string = "Hello, world!"
pattern = r"\b\w{5}\b" # 匹配长度为5的单词
match = re.match(pattern, string)
if match:
print("Found:", match.group())
else:
print("Not found.")
```
输出结果为:Not found.
需要注意的是,search函数和match函数只返回第一个匹配项。如果需要找到所有的匹配项,可以使用findall函数。另外,还可以使用sub函数进行替换匹配项。详细的用法可以查阅Python官方文档。