Home > Mobile >  How to use regex sub to replace a substring?
How to use regex sub to replace a substring?

Time:12-13

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

CodePudding user response:

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

CodePudding user response:

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
  • Related