Python re search vs match

Python re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string. Re search can also act like re match by using caret (^) in the pattern.

Here are some examples

re search vs re match

import re
print "==re.search=="
m = re.search('world', "Hello WORLD", re.I)
print m
m = re.search('^world', "Hello WORLD", re.I)
print m
print "==re.match=="
m = re.match('hello', "Hello WORLD", re.I)
print m
m = re.match('world', "Hello WORLD", re.I)
print m
==re.search==
<_sre.SRE_Match object at 0x7f1c7c3013d8>
None
==re.match==
<_sre.SRE_Match object at 0x7f1c7c3013d8>
None
Env: Python 2.7.6

re search using caret

import re
print "==re.search using caret=="
m = re.search('^hello', "Hello WORLD", re.I)
print m
m = re.search('^world', "Hello WORLD", re.I)
print m
==re.search using caret==
<_sre.SRE_Match object at 0x7f95a273d440>
None
Env: Python 2.7.6
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments