[英]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.