我想使用正则表达式搜索和替换,假设我想要一些 数字后跟“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() 遍历 line(pos 取自上一场比赛的结尾)并且然后替换,但是如何才能正确而优雅地完成呢?匹配项本身不提供方法 sub。
需要使用repl进行替换。
请注意,line 的长度会发生变化。另请注意,拆分字符串 line 会改变 '^' 在正则表达式中的含义,我想避免这种情况。
请您参考如下方法:
您可以使用函数作为替代,并让该函数执行提示。参见 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.'
可能存在这不起作用的边缘情况(例如,如果匹配的正则表达式使用环视)。
