温馨提示×

python中re.search函数的用法是什么

小亿
109
2023-10-26 02:17:57
栏目: 编程语言

re.search函数用于在字符串中搜索匹配的模式。它接受两个参数:模式和字符串。如果模式可以在字符串中找到匹配项,则返回一个匹配对象;否则返回None。

用法示例:

import re

pattern = r"abc"  # 模式字符串
string = "xyzabc123"  # 要搜索的字符串

match = re.search(pattern, string)
if match:
    print("找到匹配项:", match.group())
else:
    print("未找到匹配项")

输出:

找到匹配项: abc

在上面的示例中,re.search(pattern, string)会在字符串string中搜索模式pattern。因为字符串中存在"abc",所以re.search返回一个匹配对象,可以通过.group()方法获取匹配的字符串。如果字符串中不存在模式,则re.search返回None。

0