简体   繁体   中英

How to remove backslashes from re.sub in Python 3.9

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM