📅  最后修改于: 2020-11-06 06:22:16             🧑  作者: Mango
使用正则表达式有两个基本操作,它们看起来很相似,但有很大的不同。 re.match()仅在字符串的开头检查匹配项,而re.search()在字符串的任何位置检查匹配项。这在文本处理中起着重要作用,例如,我们经常必须编写正确的正则表达式来检索文本块以进行情感分析。
import re
if re.search("tor", "Tutorial"):
print "1. search result found anywhere in the string"
if re.match("Tut", "Tutorial"):
print "2. Match with beginning of string"
if not re.match("tor", "Tutorial"):
print "3. No match with match if not beginning"
# Search as Match
if not re.search("^tor", "Tutorial"):
print "4. search as match"
当我们运行上面的程序时,我们得到以下输出-
1. search result found anywhere in the string
2. Match with beginning of string
3. No match with match if not beginning
4. search as match