Ammar Ibraheem
Ammar Ibraheem

Reputation: 31

How to use regex sub to replace a substring?

My questions is how can I use regex sub in a way that the substituted substring is obtained by mutating the matched part? Let me explain if original string is "The most comment log in coding is Hello World" then the modified string should be "The1 most comment log in coding is Hello1 World1"

lets say regex is r'[A-Z][a-z]+'

How can I add something after or importantly in-between each match?

Please help me out here

I have tried regex sub, split etc

Upvotes: 0

Views: 70

Answers (3)

The fourth bird
The fourth bird

Reputation: 163217

You could use \g<0> to refer to the full match, and then append 1 after it.

import re
s = "The most comment log in coding is Hello World"
print(re.sub(r"[A-Z][a-z]+", r"\g<0>1", s))

Output

The1 most comment log in coding is Hello1 World1

Upvotes: 0

Madison Courto
Madison Courto

Reputation: 1277

It appears that you only wish to append the value where the word starts with a capital letter, this is an assumption but if so something like this would be fit;

import regex as re
startingString = "The most comment log in coding is Hello World"
appendedValue = "1"
pattern = re.compile(r'\b[A-Z]\w*\b')
print(pattern.sub(r'\g<0>'+appendedValue, startingString))

Output:

The1 most comment log in coding is Hello1 World1

Upvotes: 1

anmol_gorakshakar
anmol_gorakshakar

Reputation: 146

This should do the trick but you would need to provide a string

suffix="1"
x = "The most comment log in coding is Hello World"
for i in re.finditer('[A-Z][a-z]+', x):
    x = x.replace(i.group(), f"{i.group()}{suffix}")
print(x)

output

The1 most comment log in coding is Hello1 World1

Upvotes: 1

Related Questions