简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM