Rabindra
Rabindra

Reputation: 401

How to replace a substring with a regex pattern using regex in python?

I have a string "word ***.** word". And I want to replace the '***.**' with '[\d][\d][\d].[\d]+'. Unable to do it using regex as it's giving key error for '\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.

Upvotes: 0

Views: 249

Answers (1)

gruvw
gruvw

Reputation: 948

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)

Upvotes: 1

Related Questions