sparrow sparrow - 1 year ago 86
Python Question

Python re.sub with a string that contains a special character without modifying the string

My problem is that in order to do sub I need to escape a special character. But I don't want to modify the string that I'm substituting. Does Python have way to handle this?

fstring = r'C:\Temp\1_file.txt' #this is the new data that I want to substitute in
old_data = r'Some random text\n .*' #I'm looking for this in the file that I'll read
new_data = r'Some random text\n '+fstring #I want to change it to this
f = open(myfile,'r') #open the file
filedata = f.read() #read the file
f.close()
newfiledata = re.sub(old_data,new_data,filedata) #substitute the new data


An error is returned becasue the "\1" in the in "fstring" is seen as a group object.

error: invalid group reference

Answer Source

\1 would normally imply a backreference to group 1 of the regex match, but that is not what you intend here (in fact no group 1, which is the reason for the error), you'll, therefore, need to escape the string so re does not treat the \1 as a metacharacter:

fstring = r'C:\Temp\\1_file.txt'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download