code: def replace(self, html):
          
          self.html = html
          text = html.text()
          positions = []
  
          def perform_replacement(match):
              offset = sum(positions)
              start, stop = match.start() + offset, match.end() + offset
  
              s = self.html[start:stop]
              if self._is_replacement_allowed(s):
                  repl = match.expand(self.replacement)
                  self.html[start:stop] = repl
              else:
                  repl = match.group()  # no replacement takes place
  
              positions.append(match.end())
              return repl
  
          while True:
              if positions:
                  text = text[positions[-1]:]
  
              text, n = self.pattern.subn(perform_replacement, text, count=1)
              if not n:  # all is already replaced
                  break
docs: Perform replacements on given HTML fragment.