Avo Asatryan
Avo Asatryan

Reputation: 414

Replication of digits in a string using regex sub (Python)

I have a s="gh3wef2geh4ht". How can I receive s="gh333wef22geh4444ht" by using sub. I have tried this regexp. what I am doing wrong?

s=re.sub(r"(\d)",r"\1{\1}",s)

Upvotes: 4

Views: 295

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627127

You cannot use a regular expression pattern in the replacement pattern. The {...} does not copy the text captured in Group 1 n times. You need to use a lambda expression or a callback method in the re.sub to achieve what you want:

import re
s = 'gh3wef2geh4ht'
s=re.sub(r"\d", lambda m: m.group() * int(m.group()), s)
print(s)

See the Python demo

Note you do not need any capturing groups here, as the whole match is already available in Group 0.

Here, m is assigned with the curren match object, m.group() is the text value of the match and int(m.group()) is the digit cast to an int. Thus, when 3 is matched, the lambda expression does just "3" * 3 and returns as the replacement.

Upvotes: 2

akuiper
akuiper

Reputation: 215077

You can use a lambda function to capture the matched digits and repeat it:

s="gh3wef2geh4ht"
​
re.sub(r'(\d)', lambda m: m.group(1) * int(m.group(1)), s)
# 'gh333wef22geh4444ht'

Upvotes: 4

Related Questions