research的用法
re.search() 是 re 模块中的一个函数,用于在字符串中搜索匹配指定模式的内容。它返回一个匹配对象,如果找到了匹配的内容,则返回第一个匹配的结果;如果没有找到匹配的内容,则返回 None。
re.search(pattern, string, flags=0)
参数说明:
- pattern: 要匹配的正则表达式模式。
- string: 要搜索的字符串。
- flags: 可选参数,用于控制正则表达式的匹配方式,如是否区分大小写等。
使用示例:
import re
# 在字符串中查找匹配的内容
result = re.search(r'apple', 'I have an apple and a banana')
print(result) # <re.Match object; span=(9, 14), match='apple'>
# 获取匹配的内容
if result:
print(result.group()) # apple
# 使用括号分组,获取匹配的子组内容
result = re.search(r'(apple) and (banana)', 'I have an apple and a banana')
if result:
print(result.group(1)) # apple
print(result.group(2)) # banana
在上面的示例中,re.search() 函数首先在字符串 "I have an apple and a banana" 中搜索模式 "apple",找到了匹配的内容,并返回一个匹配对象。然后通过匹配对象的 group() 方法获取匹配的内容。
原文地址: https://www.cveoy.top/t/topic/i74W 著作权归作者所有。请勿转载和采集!