【问题标题】:How to replace a substring with a regex pattern using regex in python?如何在python中使用正则表达式用正则表达式模式替换子字符串?
【发布时间】: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


【解决方案1】:

这应该可以解决问题:

import re

text = 'word ***.** word'
updated_text = re.sub(re.compile(r'\*', re.I), r'[\\d]', text)
print(updated_text)

【讨论】:

  • 是的,确实如此。我试过双斜杠但错过了r。所以,它没有工作。谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-04-17
  • 2012-02-12
  • 2019-11-12
  • 2015-11-30
  • 2022-10-01
  • 2012-07-11
  • 1970-01-01
相关资源
最近更新 更多