0% found this document useful (0 votes)
12 views

8 Python Regex Match Vs Search Functions

The document discusses the difference between Python's regex match and search functions. Match checks for a match only at the beginning of a string, while search checks for a match anywhere in the string. Two examples are provided to demonstrate matching versus searching.

Uploaded by

ArvindSharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

8 Python Regex Match Vs Search Functions

The document discusses the difference between Python's regex match and search functions. Match checks for a match only at the beginning of a string, while search checks for a match anywhere in the string. Two examples are provided to demonstrate matching versus searching.

Uploaded by

ArvindSharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Python regex `match` vs.

`search` functions

Difference between Python regex match() and search() function!

WE'LL COVER THE FOLLOWING

• Python Matching Versus Searching


• Example 1
• Example 2:

Python Matching Versus Searching #


We have learned so far that Python offers two different primitive operations:

match

search

So, how they are different to each other?

Note that match checks for a match only at the beginning of a string, while
search checks for a match anywhere in the string!

Example 1 #
Let’s try to find the word Python :

#!/usr/bin/python
import re

line = "Learn to Analyze Data with Scientific Python";

m = re.search( r'(python)', line, re.M|re.I)

if m:
print "m.group() : ", m.group()
else:
print "No match by obj.search!!"

m = re.match( r'(python)', line, re.M|re.I )


if m:
print "m.group() : ", m.group()

else:
print "No match by obj.match"

You will be able to see that, match function won’t find the word “Python”, but
search can! Also note the use of the re.I (case insensitive) option.

Example 2: #

#!/usr/bin/python
import re

email = "hello@leremove_thisarntoanalayzedata.com ";

# m = re.match ("remove_this", email) // This will not work!


m = re.search("remove_this", email)

if m:
print "email address : ", email[:m.start()] + email[m.end():]
else:
print "No match!!"

You might also like