【问题标题】:How to remove backslashes from re.sub in Python 3.9如何在 Python 3.9 中从 re.sub 中删除反斜杠
【发布时间】:2021-06-08 13:23:42
【问题描述】:

为什么我从我的正则表达式搜索和替换代码中得到这个反斜杠? 如果我不使用任何特殊字符,我将不会得到它们。

问题是如何去掉这个反斜杠?

结果:

[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

【问题讨论】:

    标签: python python-3.x regexp-replace


    【解决方案1】:

    如果这不是你想要的,你为什么要re.escape 替换字符串?

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

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

    这里的 Python 行为实际上存在一些怪癖。 re.escape 可能不应该反斜杠转义字符类之外的文字破折号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-23
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      • 2016-06-16
      相关资源
      最近更新 更多