代码之家  ›  专栏  ›  技术社区  ›  Lukasz

Regex:仅替换一个事件

  •  2
  • Lukasz  · 技术社区  · 10 年前

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

    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_1 .

    2 回复  |  直到 10 年前
        1
  •  4
  •   TigerhawkT3    10 年前

    对于这样的简单表达式,您可以使用 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.'
    
        2
  •  3
  •   vks    10 年前
    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`