0

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

0

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.