简体   繁体   English

添加确认以在Python中使用正则表达式进行搜索和替换

[英]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. 我有一个小的python脚本循环遍历一堆文件,并在每个文件中应用一些正则表达式。 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). 现在,在一个字符串中,我正在做一个.search 。,然后是匹配文本中的.sub ,如果用户确认我在原始字符串中插入新文本(通过索引)。

You could use re.sub with a callback that ask the user's confirmation: 你可以使用带有回调的re.sub来询问用户的确认:
http://docs.python.org/2/library/re.html#text-munging 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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