Python Tutorial

Thursday, August 11, 2011

python reqular expression re.findall()

re.findall() is very similar to re.search. Only difference is re.search() looking for first instance but re.findall() for all instance match with this expression.
Lets see some example:
import re 

#find all one or more r
m=re.findall(r'r+','tomorrow rrow RRO')
print m

#find all one or more r ignorecase
m=re.findall(r'r+','tomorrow rrow RRO',re.IGNORECASE)
print m

#find all two consecutive digits
m=re.findall(r'\d\d','tomorrow123  foo89')
print m

#find all email from string
m=re.findall(r'[\w.-_]+@[\w.]+','test 123 . @ test.cse@gmail.com test
test@yahoo.com test_tester@yahoo.com test-123@yahoo.com') print m



Output:
['rr', 'rr']
['rr', 'rr', 'RR']
['12', '89']
['test.cse@gmail.com', 'test@yahoo.com', 'test_tester@yahoo.com', '123@yahoo.com']

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.