Python - 搜索和匹配



在使用正则表达式时,有两个经常混淆的基本操作,但它们的显著差异。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
广告