简体   繁体   English

如何从 Python 3.9 中的 re.sub 中删除反斜杠

[英]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) Arch linux(5.11.4-arch1-1 x64)

Python 3.9.2 Python 3.9.2

Why do you re.escape the replacement string if that's not what you want?如果这不是您想要的,为什么要re.escape替换字符串?

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). re.escape仅对将文字字符串转换为正则表达式有意义,但re.sub中的替换参数不是正则表达式,它只是一个字符串(有几个特殊情况,例如您在此处使用的反向引用)。

    text = re.sub(r'(const char pass\[\] = \").*(\")', r'\1' + replace_string + r'\2', text)

There are actually some quirks in Python's behavior here. Python 的行为在这里实际上有一些怪癖。 re.escape should perhaps not backslash-escape a literal dash outside of a character class. re.escape可能不应该反斜杠转义字符 class 之外的文字破折号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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