Monday, October 10, 2011

Python RE

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

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

f1 = open("data2","r")
f2 = open("changedfile","w")

for searchstr in f1.readlines():
#The count is optional, this will change the number of occurance in the line.
#IF count is not given it will change every match in that line
  print re1.sub("Changed_here",searchstr,count = 2)
  changed = re1.sub("Changed_here",searchstr,count = 2)
  f2.writelines(changed)

#END

Output

bala@bala-laptop:~/python$ cat data2
4562
234
 15.00
 1
234.234.234.234

bala@bala-laptop:~/python$ python RE.py
Changed_here

Changed_here

 Changed_here.Changed_here

 Changed_here

Changed_here.Changed_here.234.234

bala@bala-laptop:~/python$ cat changedfile
Changed_here
Changed_here
 Changed_here.Changed_here
 Changed_here
Changed_here.Changed_here.234.234

bala@bala-laptop:~/python$

No comments:

Post a Comment