正则表达式:仅替换一次

时间:2016-01-11 05:58:30

标签: python regex matching

我试图使用正则表达式替换字符串中特定单词的一个实例,其中需要替换的单词至少出现两次。例如,我有以下内容:

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

到目前为止,我有:

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)

我遇到的问题是,在使用names_regex_noun.sub(noun, content)时,它正在替换NOUNcontent的两个实例。我只想替换第一个NOUN并保持noun_1不受影响,以便{{1}}替换它。

2 个答案:

答案 0 :(得分:4)

对于这样的简单表达式,您只需将str.replace()与指定的count一起使用:

>>> content = 'The NOUN is ADJECTIVE and is completely different from the NOUN.'
>>> noun = 'bird'
>>> content.replace('NOUN', noun, 1)
'The bird is ADJECTIVE and is completely different from the NOUN.'

答案 1 :(得分:3)

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

输出:abc abc

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

use `count=1`