Python 正则表达式:仅替换一个引用
我试图用正则表达式替换字符串中特定单词的一个实例,其中需要替换的单词至少出现两次。例如,我有以下几点:Python 正则表达式:仅替换一个引用,python,regex,matching,Python,Regex,Matching,我试图用正则表达式替换字符串中特定单词的一个实例,其中需要替换的单词至少出现两次。例如,我有以下几点: 这个名词是形容词,与名词完全不同。 到目前为止,我已经: 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
这个名词是形容词,与名词完全不同。
到目前为止,我已经:
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\u regex\u noun.sub(noun,content)
时,它正在替换content
中的noun
的两个实例。我只想替换第一个实例,而不影响NOUN
的第二个实例,这样它就可以被NOUN\u 1
替换 对于这样的简单表达式,您只需与指定的计数一起使用即可:
>>> 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.'
输出:abc
re.sub(pattern, repl, string, count=0, flags=0)`
use `count=1`
re.sub(pattern, repl, string, count=0, flags=0)`
use `count=1`