Python - Recherche et correspondance

En utilisant des expressions régulières, il existe deux opérations fondamentales qui semblent similaires mais présentent des différences significatives. lere.match() recherche une correspondance uniquement au début de la chaîne, tandis que re.search()recherche une correspondance n'importe où dans la chaîne. Cela joue un rôle important dans le traitement de texte car nous devons souvent écrire l'expression régulière correcte pour récupérer le morceau de texte à des fins d'analyse sentimentale à titre d'exemple.

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"

Lorsque nous exécutons le programme ci-dessus, nous obtenons la sortie suivante -

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