Search & Replace with RegEx

tchurm at gmail.com tchurm at gmail.com
Tue Jul 12 11:50:56 EDT 2005


thanks for the comments + help.

i think i got it working, although it's not pretty:

##############################
import os
import re

theRegEx = '.*abs:.*\.*.\\\\'

p = re.compile(theRegEx, re.IGNORECASE)

fileToSearch  = 'compreg.dat'
print "File to perform search-and-replace on: " + fileToSearch
print "Using Regex: " + theRegEx
print ""

#set this to an empty string
newdoc = ""

if os.path.isfile( fileToSearch ):
	x = open(fileToSearch, "r")
	while 1:
		line = x.readline()
		if(p.match(line)!=None):
			print ""
			print line
			newdoc = newdoc + re.sub("abs:.*\.*.\\\\", "rel:", line)
		else:	newdoc = newdoc + line
		if line == "":
			print ""
			print "finished !"
			break

x.close()

if newdoc != '':
	x = open(fileToSearch, "w")
	x.write(newdoc)
	x.close()
	print ""
	print "file written!"


raw_input( '\n\nPress Enter to exit...' )
##############################




More information about the Python-list mailing list