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)

#Match will look only at the start of the string
match1 = re1.match(searchstr)
#Search will look even in the middle of the string
search = re1.search(searchstr)
#Findall will look even look for additional matches in the string
findall = re1.findall(searchstr)

if match1:
   print "match1 Matching \d+\s+\w+ : ",match1.group()
if search:
   print "Search matching \d+\s+\w+ : ",search.group()
if findall:
   print "Findall matchin \d+\s+\w+ : ",findall
else:
   print "No search match"

#END

Output

bala@bala-laptop:~/python$ python RE.py
Enter a searching string '\d+\s+\w+' : 500 apples
*********************************
searchstr =  500 apples
*********************************
match1 Matching \d+\s+\w+ :  500 apples
Search matching \d+\s+\w+ :  500 apples
Findall matchin \d+\s+\w+ :  ['500 apples']

bala@bala-laptop:~/python$ python RE.py
Enter a searching string '\d+\s+\w+' : Those are 500 toys
*********************************
searchstr =  Those are 500 toys
*********************************
Search matching \d+\s+\w+ :  500 toys
Findall matchin \d+\s+\w+ :  ['500 toys']

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



No comments:

Post a Comment