首页 > 解决方案 > 正则表达式无法匹配python中的特殊符号

问题描述

我有一个字符串: s = "we are \xaf\x06OK\x03family, good",我想用 '' 替换\xaf,\x06\x03'',正则表达式是pat = re.compile(r'\\[xX][0-9a-fA-F]+'),但它不能匹配任何东西。代码如下:

pat = re.compile(r'\\[xX][0-9a-fA-F]+')
s = "we are \xaf\x06OK\x03family, good"
print(s)
print(re.sub(pat, '', s))

结果是

we are ¯OKfamily, good we are ¯OKfamily, good,

但我怎么能得到we are OK family, good

标签: pythonregex

解决方案


您必须将输入string s视为原始字符串,然后才能工作,请参见下面的示例:

pat = re.compile(r'\\[xX][0-9a-fA-F].')
s = r"we are \xaf\x06OK\x03family, good"
print(s)
print(re.sub(pat, '', s))

推荐阅读