[英]Regex Difference Python2 and Python3
我想將此代碼從 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" 也無濟於事。 那么它不會取代它。
采用
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 中的正則表達式更輕松。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.