Monday, October 10, 2011

Python RE

#!/usr/bin/python
#Author: Balasubramaniam Natarajan
#Demonstrate how to use Regular Expression
import re

def search(searchstr):
    print "*********************************"
    print "searchstr = ", searchstr
    print "*********************************"

searchstr = raw_input("Enter a searching string '\d+\s+\w+' : ")
search(searchstr)

re1 = re.compile('\d+\s+\w+',re.IGNORECASE)

#Finditer will return a search which we are iterate through
finditer = re1.finditer(searchstr)

if finditer:
   for i in finditer:
    print i.group()
else:
   print "No search match"

#END

Output

bala@bala-laptop:~/python$ python RE.py
Enter a searching string '\d+\s+\w+' : Those are 500 toys, 100 games and 20 infants
*********************************
searchstr =  Those are 500 toys, 100 games and 20 infants
*********************************
500 toys
100 games
20 infants
bala@bala-laptop:~/python$

No comments:

Post a Comment