Search code examples
pythonregexpreviewsubstitutionconfirmation

Add confirmation to search and replace using regex in Python


I have a small python script that loops through a bunch of files and in each file apply a few regex. I would like to add a confirmation step in which the old and the new text are shown. Is there any efficient way of doing this. Right now, in a string, I am doing a .search., then a .sub within the matched text and the if the user confirms I insert the new text in the original string (by indices).


Solution

  • You could use re.sub with a callback that ask the user's confirmation:
    http://docs.python.org/2/library/re.html#text-munging

    text = 'This is a dummy dummy text'
    
    def callback(m):
        string = m.group()
        subst = string.upper()
        start = m.start()
        question = 'subst {:s} at pos {:d}:'.format(string, start)
        ans = raw_input(question)
        if ans[0] in 'Yy':
            return subst
        else:
            return string
    
    print re.sub(r'\bdummy\b', callback, text)
    

    which print

    subst dummy at pos 10:n
    subst dummy at pos 16:y
    This is a dummy DUMMY text