![](/img/trans.png)
[英]How to avoid re.sub processing backslashes in replacement string in python 3.10.5?
[英]How to remove backslashes from re.sub in Python 3.9
為什么我從我的正則表達式搜索和替換代碼中得到這個反斜杠? 如果我不使用任何特殊字符,我將不會得到它們。
問題是如何刪除這個反斜杠?
結果:
[bash]$ python /home/lucki1000/ESP/sr.py |grep "const char pass"
const char pass[] = "TESTpassword\.\-2"
我的預期:
const char pass[] = "TESTpassword.-2"
我的代碼:
import re
replace_string = "TESTpassword.-2"
fname = "/home/lucki1000/ESP/adv.txt"
with open(fname, 'r+') as f:
text = f.read()
text = re.sub(r'(const char pass\[\] = \").*(\")', r'\1' + re.escape(replace_string) + r'\2', text)
f.seek(0)
print(text)
f.write(text)
f.truncate()
如果需要的話:
Arch linux(5.11.4-arch1-1 x64)
Python 3.9.2
如果這不是您想要的,為什么要re.escape
替換字符串?
re.escape
僅對將文字字符串轉換為正則表達式有意義,但re.sub
中的替換參數不是正則表達式,它只是一個字符串(有幾個特殊情況,例如您在此處使用的反向引用)。
text = re.sub(r'(const char pass\[\] = \").*(\")', r'\1' + replace_string + r'\2', text)
Python 的行為在這里實際上有一些怪癖。 re.escape
可能不應該反斜杠轉義字符 class 之外的文字破折號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.