Python Tutorial

Thursday, August 11, 2011

python reqular expression re.search()

re.search() is used for search pattern into string, it's return the corresponding match object. Let's got to some example:

At first we need to write a function named printMatch, i think very shortly you will know why this function is for :)


import re

def printMatch(m):
    if m:
        print m.group(0)
    else:
        print "Not Found"

#search one or more r
m=re.search(r'r+','tomorrow')
printMatch(m)

#search two consecutive digits
m=re.search(r'\d\d','tomorrow123')
printMatch(m)

#after find a digit go rest of the word
m=re.search(r'\d\w+','tomorrow123 foo')
printMatch(m)

#need to match from start index
m=re.search(r'^\d\w+','tomorrow123 foo')
printMatch(m)

#need to match from start index
m=re.search(r'^\d\w+','456tomorrow123')
printMatch(m)

#only search for non numeric character
m=re.search(r'\D*','tomoRRo._+#w123 foo')
printMatch(m)

#try yourself
m=re.search(r'\d*\s*\d*\s','tom123    45 foo')
printMatch(m)

#filter email address from string
m=re.search(r'[\w.]+@[\w.]+','test 123 . @ jony.cse@gmail.com test')
printMatch(m)

#any character after m
m=re.search(r'm.+','tomorrow foo')
printMatch(m)




Output:
rr
12
123
Not Found
456tomorrow123
tomoRRo._+#w
123    45 
jony.cse@gmail.com
morrow foo



Finally:
There are lots of way to use re.search() in python, I am just showing you some them. Hope it will help you to explore it.

0 comments:

Post a Comment