正则表达式 match() 和 regex search() 函数在 Python 中的重要性
使用 正则表达式有两种类型的操作,(a) 搜索和 (b) 匹配。为了在查找模式和与该模式匹配时有效地使用正则表达式,可以使用这两个函数。
让我们考虑我们有一个字符串。正则表达式 match() 仅检查字符串开头的模式,而 正则表达式 search() 检查字符串中任何位置的模式。如果找到模式,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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程语言
C++
C#
MongoDB
MySQL
Javascript
PHP