Python Search and Match

Searching and Matching in Python

There are two basic operations using regular expressions that appear similar but have significant differences. re.match() checks for a match only at the beginning of a string, while re.search() checks for a match anywhere in the string. This plays an important role in text processing, as we often need to write correct regular expressions to retrieve sections of text for sentiment analysis.

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"

When we run the above program, we get the following output –

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

Leave a Reply

Your email address will not be published. Required fields are marked *