Python - Search and Match
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 −
|Topics You May Be Interested In|
|Python Tuples||Python - Http Authentication|
|Python Quick Guide||Python - Building Urls|
|Python - Ds Environment||Python - Ssh|
|Python - Arrays||Python - Search And Match|
|Python - Divide And Conquer||Python Tuples|
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