Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Replacing only one occurrence

I'm trying to replace only one instance of a specific word in a string using regex, where the word that needs to be substituted appears at least twice. For instance I have the following:

The NOUN is ADJECTIVE and is completely different from the NOUN.

so far I have:

content = 'The NOUN is ADJECTIVE and is completely different from the NOUN.'   

noun = input('Enter a noun: ')
adj = input('Enter an adjective: ')
noun_1 = input('Enter another noun: ')

names_regex_noun = re.compile(r'NOUN')
content = names_regex_noun.sub(noun, content)
names_regex_adj = re.compile(r'ADJECTIVE')
content = names_regex_adj.sub(adj, content)
names_regex_noun_1 = re.compile(r'NOUN')
content = names_regex_noun_1.sub(noun_1, content) 
print(content)

The problem that I'm having is that when using names_regex_noun.sub(noun, content) it is replacing both instances of NOUN in content. I would like to only replace the first and leave the second instance of NOUN unaffected so that it could be substituted by noun_1.

like image 484
Lukasz Avatar asked Jun 08 '26 18:06

Lukasz


1 Answers

x="abc abc abc"
print re.sub(r"abc\s*","",x,count=1)

Output:abc abc

re.sub(pattern, repl, string, count=0, flags=0)` 

use `count=1`
like image 177
vks Avatar answered Jun 10 '26 07:06

vks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!