交互替代回复sub()带pos?

2024-04-20 04:27:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用正则表达式来搜索和替换,比如说我想让一些数字后跟'm'。你知道吗

import re
pattern = '(\d)'
repl = r'\1 m'
line = 'Each of the 2 cars is 5 long.'

因为一个简单的

re.sub(pattern, repl, line)

无法给出所需的结果,我希望以交互方式执行此操作,即用户必须确认每个替换,显示字符串的相应部分及其周围的几个字符。这可以很容易地用match.start()等实现

使用re.compile(),我们得到了search()等带有有用参数pos的方法,但对于sub()来说,这是不存在的。示例:

regex = re.compile(pattern)
regex.match(line, pos=15)
regex.sub(repl, line, count=1)

可以使用regex.finditer()(从上一个匹配的末尾取pos)在line上循环,然后替换,,但是如何才能正确而优雅地做到这一点呢?匹配本身不提供方法sub。你知道吗

需要使用repl进行替换。你知道吗

注意line的长度会改变。还要注意,拆分字符串line会改变正则表达式中'^'的含义,这是我要避免的。你知道吗


Tags: ofthe方法字符串posimportrematch
1条回答
网友
1楼 · 发布于 2024-04-20 04:27:23

您可以使用函数作为替换,并让该函数执行提示。有关替换函数的工作方式,请参见the documentation。下面是一个简单的例子:

def confirmSub(match):
    print("Going to replace", match.string[match.start()-5:match.end()+5])
    x = raw_input("OK?")
    if x.lower().startswith("y"):
        return match.group() + "m"
    return match.group()

下面是它在您的示例中的工作方式:

>>> re.sub(r'\d', confirmSub, "Each of the 2 cars is 5 long.")
Going to replace  the 2 cars
OK?n
Going to replace s is 5 long
OK?y
'Each of the 2 cars is 5m long.'

如果希望能够传入替换模式,可以通过使confirmSub函数接受替换模式并返回使用该模式的替换函数来详细说明这一点:

def confirmSub(replacement):
    def confirmer(match):
        print("Going to replace", match.string[match.start()-5:match.end()+5])
        x = raw_input("OK?")
        if x.lower().startswith("y"):
            return re.sub(match.re.pattern, replacement, match.group())
        return match.group()
    return confirmer

然后:

>>> re.sub(r'(\d)', confirmSub(r"\1m"), "Each of the 2 cars is 5 long.")
Going to replace  the 2 cars
OK?n
Going to replace s is 5 long
OK?y
'Each of the 2 cars is 5m long.'

可能存在这样做行不通的边缘情况(例如,如果匹配的regex使用lookarounds)。你知道吗

相关问题 更多 >