How to find and replace nth occurrence of word in a sentence using python regular expression?

后端 未结 7 2365
广开言路
广开言路 2020-12-01 11:00

Using python regular expression only, how to find and replace nth occurrence of word in a sentence? For example:

str = \'cat goose  mouse horse pig cat cow\'         


        
相关标签:
7条回答
  • 2020-12-01 12:00

    I would define a function that will work for every regex:

    import re
    
    def replace_ith_instance(string, pattern, new_str, i = None, pattern_flags = 0):
        # If i is None - replacing last occurrence
        match_obj = re.finditer(r'{0}'.format(pattern), string, flags = pattern_flags)
        matches = [item for item in match_obj]
        if i == None:
            i = len(matches)
        if len(matches) == 0 or len(matches) < i:
            return string
        match = matches[i - 1]
        match_start_index = match.start()
        match_len = len(match.group())
    
        return '{0}{1}{2}'.format(string[0:match_start_index], new_str, string[match_start_index + match_len:])
    

    A working example:

    str = 'cat goose  mouse horse pig cat cow'
    ns = replace_ith_instance(str, 'cat', 'Bull', 2)
    print(ns)
    

    The output:

    cat goose  mouse horse pig Bull cow
    

    Another example:

    str2 = 'abc abc def abc abc'
    ns = replace_ith_instance(str2, 'abc\s*abc', '666')
    print(ns)
    

    The output:

    abc abc def 666
    
    0 讨论(0)
提交回复
热议问题