Reputation: 87
Why I get this backslashes from my regex search and replace code? If i won't use any special char I won't get them.
The question is how to remove this backslashes?
result:
[bash]$ python /home/lucki1000/ESP/sr.py |grep "const char pass"
const char pass[] = "TESTpassword\.\-2"
what I expected:
const char pass[] = "TESTpassword.-2"
my code:
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()
If needed:
Arch linux(5.11.4-arch1-1 x64)
Python 3.9.2
Upvotes: 0
Views: 366
Reputation: 189377
Why do you re.escape
the replacement string if that's not what you want?
re.escape
only makes sense for turning a literal string into a regex, but the replacement argument in re.sub
is not a regex, it's just a string (with a couple of special cases, like the backreferences you are using here).
text = re.sub(r'(const char pass\[\] = \").*(\")', r'\1' + replace_string + r'\2', text)
There are actually some quirks in Python's behavior here. re.escape
should perhaps not backslash-escape a literal dash outside of a character class.
Upvotes: 2