6 Python Regex Search Function
6 Python Regex Search Function
Match Flags #
Modifier Description
Performs case-insensitive
re.I
matching.
Return values #
The re.search function returns a match object on success and None
upon failure. -
Use group(n) or groups() function of match object to get matched
expression, e.g., group(n=0) returns entire match (or specific subgroup
n)
Example 1 #
Let’s find the words before and after the word to :
#!/usr/bin/python
import re
if m:
print "m.group() : ", m.group()
print "m.group(1) : ", m.group(1)
print "m.group(2) : ", m.group(2)
else:
print "No match!!"
The first group (.*) identified the string: Learn and the next group (*.?)
identified the string: Analyze.
Example 2 #
groups([default]) returns a tuple containing all the subgroups of the match,
from 1 up to however many groups are in the pattern.
#!/usr/bin/python
import re
if m:
print "m.group() : ", m.groups()
print "m.group (1,2)", m.group(1, 2)
else:
print "No match!!"
Example 3 #
groupdict([default]) returns a dictionary containing all the named
subgroups of the match, keyed by the subgroup name.
#!/usr/bin/python
!/us /b /pyt o
import re
number = "124.13";
if m:
print "m.groupdict() : ", m.groupdict()
else:
print "No match!!"
Example 4 #
start([group]) and end([group]) return the indices of the start and end of
the substring matched by group . We need to use search instead of match for
this example:
#!/usr/bin/python
import re
if m:
print "email address : ", email[:m.start()] + email[m.end():]
else:
print "No match!!"
Show Hint