python - 正则表达式无法匹配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
解决方案
您必须将输入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))
推荐阅读
- reactjs - 404 未找到 - 获取 https://registry.npmjs.org/firebase-database - 未找到
- python - 在 Tkinter 的子菜单中创建子菜单
- android - 使用改造和共享偏好注销
- c# - 如何使用 Razor 页面中的模型绑定验证来验证日期是否过去
- scala - Akka-Http 客户端在请求进行时关闭连接池
- java - 3 个实体之间的多对一关系
- javascript - 如何在javascript中将对象内的元素打印为字符串?
- c# - 如何将变量中的数据保存到文件中?
- f# - 我有两个长度不同的列表(列表 a 和列表 b),如何获得包含列表 a 的所有唯一元素的新列表?
- sql - 如何使用 PostgreSQL 的内部变量和函数通过查询获取新访问记录的数据?