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

后端 未结 7 2419
广开言路
广开言路 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 11:51

    Create a repl function to pass into re.sub(). Except... the trick is to make it a class so you can track the call count.

    class ReplWrapper(object):
        def __init__(self, replacement, occurrence):
            self.count = 0
            self.replacement = replacement
            self.occurrence = occurrence
        def repl(self, match):
            self.count += 1
            if self.occurrence == 0 or self.occurrence == self.count:
                return match.expand(self.replacement)
            else:
                try:
                    return match.group(0)
                except IndexError:
                    return match.group(0)
    

    Then use it like this:

    myrepl = ReplWrapper(r'Bull', 0) # replaces all instances in a string
    new_str = re.sub(r'cat', myrepl.repl, str)
    
    myrepl = ReplWrapper(r'Bull', 1) # replaces 1st instance in a string
    new_str = re.sub(r'cat', myrepl.repl, str)
    
    myrepl = ReplWrapper(r'Bull', 2) # replaces 2nd instance in a string
    new_str = re.sub(r'cat', myrepl.repl, str)
    

    I'm sure there is a more clever way to avoid using a class, but this seemed straight-forward enough to explain. Also, be sure to return match.expand() as just returning the replacement value is not technically correct of someone decides to use \1 type templates.

提交回复
热议问题