搜索
Coddy Python 正则表达式 课程的第 3 课,共 28 课。
findall 函数会以列表形式返回所有匹配项,而 search 函数会在字符串中搜索匹配模式,并将第一个匹配项作为匹配对象返回。
re.search(pattern, string)- pattern:你要搜索的正则表达式模式。
- string:你要在其中搜索该模式的字符串。
import re
text = "Hello, world!"
pattern = "world"
match = re.search(pattern, text)
if match:
print("Match found:", match.group()) # 输出:Match found: world
else:
print("No match found")在上面的示例中,我们在字符串 text 中搜索单词 "world"。search 函数会返回一个匹配对象,我们使用 group() 方法提取匹配的文本。
挑战
简单编写一个程序,使用 search 函数检查字符串 s 是否包含单词 w。如果该单词存在,就输出 "Found",否则输出 "Not found"。
亲手试试
import re
s = input()
w = input()
# 在这里编写代码Python 正则表达式中的所有课
自己练习: Python 在线编译器
用你自己的文本测试正则: 正则表达式测试器