2017-07-26 244 views
-1

我的问题是,为了做子我需要转义特殊字符。但我不想修改我替换的字符串。 Python有办法处理这个吗?返回Python re.sub中包含特殊字符而不修改字符串的字符串

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 

错误becasue在在“\ 1”“一个fstring”被看作是一个组对象。

error: invalid group reference 
+1

I *认为*您可能需要在原始字符串中转义它。你可以试试'fstring = r'C:\ Temp \\ 1_file.txt''? –

+0

谢谢,这有效,但由于我在很多文件中阅读,我不想编写额外的代码来修改每个文件,如果我可以避免它。猜猜这不是什么大问题。 – sparrow

+0

呃,这个网站有时候很烦人。为什么要投票? – sparrow

回答

1

逃生最终反斜线:

new_data = r'Some random text\n ' + fstring.replace('\\', r'\\') 
+0

谢谢,这正是我需要的。 – sparrow

0

\1通常意味着一个反向引用正则表达式匹配的1组,但是这不是你想要什么这里(其实没有第1组,这是错误的原因),你会因此, ,需要逃跑的字符串,因此re不能治疗\1元字符:

fstring = r'C:\Temp\\1_file.txt' 
+0

我试过了,问题在于它改变了我替换的字符串:C \:\ Temp \ NA_CA_logs \ 1_file \ .txt – sparrow

+0

@sparrow它没有,尝试'打印'结果。 –

+0

@sparrow那个脑袋。还有其他元字符。你可以简单地将斜杠加倍,所以它只能转义'\ 1'。答案更新:) –

相关问题