Python - Search and Match


Advertisements

Using regular expressions there are two fundamental operations which appear similar but have significant differences. The re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string. This plays an important role in text processing as often we have to write the correct regular expression to retrieve the chunk of text for sentimental analysis as an example.

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

Useful Video Courses


Video

Python Online Training

187 Lectures 17.5 hours

Malhar Lathkar

Video

Python Essentials Online Training

55 Lectures 8 hours

Arnab Chakraborty

Video

Learn Python Programming in 100 Easy Steps

136 Lectures 11 hours

In28Minutes Official

Video

Python with Data Science

Best Seller

75 Lectures 13 hours

Eduonix Learning Solutions

Video

Python 3 from scratch to become a developer in demand

Best Seller

70 Lectures 8.5 hours

Lets Kode It

Video

Python Data Science basics with Numpy, Pandas and Matplotlib

Most Popular

63 Lectures 6 hours

Abhilash Nelson

Advertisements