2017-07-26 243 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'。答案更新:) –

相關問題