[英]How to replace a substring with a regex pattern using regex in python?
I have a string "word ***.** word"
.我有一个字符串"word ***.** word"
。 And I want to replace the '***.**'
with '[\\d][\\d][\\d].[\\d]+'
.我想用'[\\d][\\d][\\d].[\\d]+'
替换'***.**'
'[\\d][\\d][\\d].[\\d]+'
。 Unable to do it using regex as it's giving key error for '\\d'
.无法使用正则表达式执行此操作,因为它为'\\d'
提供了关键错误。 My code is:我的代码是:
text = 'word ***.** word'
updated_text = re.sub(re.compile(r'\b\*\*\*\b', re.I), '[\d][\d][\d]', text)
I'm getting this error:我收到此错误:
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'
I know that my code is not correct.我知道我的代码不正确。 But I can't think of any different way.但我想不出任何不同的方式。 Didn't find anything in the community blogs, as well.在社区博客中也没有找到任何内容。
This should do the trick:这应该可以解决问题:
import re
text = 'word ***.** word'
updated_text = re.sub(re.compile(r'\*', re.I), r'[\\d]', text)
print(updated_text)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.