【问题标题】:Regex Difference Python2 and Python3正则表达式区别 Python2 和 Python3
【发布时间】:2021-10-01 10:33:00
【问题描述】:

我想将此代码从 python2 移植到 python3

p = re.compile(ur"(?s)<u>(.*?)<\/u>")
subst = "\underline{\\1}"
raw_html = re.sub(p, subst, raw_html)

我已经发现ur 应该改为r

p = re.compile(r"(?s)<u>(.*?)<\/u>")
subst = "\underline{\\1}"
raw_html = re.sub(p, subst, raw_html)

但是它不起作用它抱怨这个:

cd build && PYTHONWARNINGS="ignore" python3 ../src/katalog.py --katalog 1
Traceback (most recent call last):
  File "src/katalog.py", line 11, in <module>
    from common import *
  File "src/common.py", line 207
    subst = "\underline{\\1}"
                             ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \uXXXX escape
make: *** [katalog1] Error 1

但是将其更改为 "\underline" 也无济于事。那时它不会取代它。

【问题讨论】:

    标签: python python-3.x regex python-2.x


    【解决方案1】:

    使用

    import re
    raw_html = r"<u>1</u> and <u>2</u>"
    p = re.compile(r"(?s)<u>(.*?)</u>")
    subst = r"\\underline{\1}"
    raw_html = re.sub(p, subst, raw_html)
    print(raw_html)
    

    查看Python proof,结果为\underline{1} and \underline{2}。基本上,在替换内部,使用双反斜杠替换为单个反斜杠。在 Python 中使用原始字符串文字让生活更轻松。

    【讨论】:

    • 绝对正确。感谢您的澄清!
    猜你喜欢
    • 1970-01-01
    • 2013-07-26
    • 2016-11-18
    • 2012-02-22
    • 2016-03-12
    • 2023-04-07
    • 2015-06-13
    • 1970-01-01
    相关资源
    最近更新 更多