Find and replace multiple RegEx search expressions

Peter Otten __peter__ at web.de
Tue Mar 18 05:48:03 EDT 2014


Jignesh Sutar wrote:

> Hi,
> 
> I'm trying to delete contents of a .txt log file, matching on multiple
> re.sub criteria but not sure how to achieve this.
> 
> Below is an illustration of what I am trying to achieve (of course in this
> example I can combine the 3 re.sub into a single re expression but my
> actual code will have a dozen plus expression I need to match on so easier
> to keep them separate). Only the last re.sub will take effect in the
> example below I need all 3 to take effect.
> 
> 
> import re
> o = open(r"c:\temp\outputfile.txt","w")
> data = open(r"C:\Temp\infile.txt").read()
> o.write( re.sub(".*<X>     ","",data) )
> o.write( re.sub(".*<Y>     ","",data) )
> o.write( re.sub(".*<Z>     ","",data) )
> o.close()

Apply all substitutions to data before you write the result to the file:

with open(infile) as f:
    data = f.read()

for expr in list_of_regexes:
    data = re.sub(expr, "", data)

with open(outfile, "w") as f:
    f.write(data)





More information about the Python-list mailing list