Python 中 regex match() 和 regex search() 函数的重要性
pythonserver side programmingprogramming更新于 2024/2/18 18:57:00
使用 regex 可以执行两种类型的操作,(a) 搜索和 (b) 匹配。为了在查找模式并与模式匹配时有效地使用 regex,我们可以使用这两个函数。
假设我们有一个字符串。regex match() 仅在字符串的开头检查模式,而 regex search() 则在字符串的任何位置检查模式。如果找到模式,match() 函数将返回 match 对象,否则不返回任何模式。
- match() – 仅在字符串的开头查找模式并返回匹配的对象。
- search() –检查字符串中任意位置的模式并返回匹配的对象。
在此示例中,我们有一个字符串,我们需要在此字符串中找到单词"engineer"。
示例
import re pattern = "Engineers" string = "Scientists dream about doing great things. Engineers Do them" result = re.match(pattern, string) if result: print("Found") else: print("Not Found")
运行此代码将打印输出为,
输出
Not Found
现在,让我们使用上述示例进行搜索,
示例
import re pattern = "Engineers" string = "Scientists dream about doing great things. Engineers Do them" result = re.search(pattern, string) if result: print("Found") else: print("Not Found")
运行上述代码将打印输出为,
输出
Found