【发布时间】:2021-06-17 07:39:42
【问题描述】:
我有一个字符串"word ***.** word"。我想用'[\d][\d][\d].[\d]+' 替换'***.**'。无法使用正则表达式执行此操作,因为它为'\d' 提供了关键错误。
我的代码是:
text = 'word ***.** word'
updated_text = re.sub(re.compile(r'\b\*\*\*\b', re.I), '[\d][\d][\d]', text)
我收到此错误:
Traceback (most recent call last):
File "/usr/lib/python3.8/sre_parse.py", line 1039, in parse_template
this = chr(ESCAPES[this][1])
KeyError: '\\d'
我知道我的代码不正确。但我想不出任何不同的方法。在社区博客中也没有找到任何东西。
【问题讨论】:
-
使用原始字符串并双重转义反斜杠
updated_text = re.sub(re.compile(r'\b\*\*\*\b', re.I), r'[\\d][\\d][\\d]', text)
标签: python python-3.x regex