python - 正则表达式:仅替换一次

标签 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) 时它正在替换 NOUN 的两个实例在 content .我只想替换第一个并保留 NOUN 的第二个实例不受影响,因此可以用 noun_1 代替.

最佳答案

对于像这样的简单表达式,你可以只使用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.'

关于python - 正则表达式:仅替换一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34715067/

相关文章:

python - 从宽到长返回空输出 - Python 数据框

python - Discord API,get_member(user_id) 错误

python - Pandas 分组和减少 DataFrame

python - 在python中用占位符替换字符串

php - 在另一个词之前或之后获取一个词

python - 在带加量词的字符范围后,负前瞻不起作用

regex - 在 CORS 中使用正则表达式

java - 正则表达式要放置 ?或者 !如果在原始单词中检测到

scala - Scala 中可以匹配范围吗?

ios - 快速获取字符串中子字符串的所有范围