TL;DR:如何让re.sub
打印出它所做的替换,包括当使用组时?
有点像有一个详细的选项,有没有可能有re.sub
打印出一个消息,每次它作出替换?这对于测试多行re.sub
行如何与大文本交互非常有用.
利用repl
参数可以是一个函数这一事实,我设法为简单的替换想出了这个解决方法:
import re
def replacer(text, verbose=False):
def repl(matchobj, replacement):
if verbose:
print(f"Replacing {matchobj.group()} with {replacement}...")
return replacement
text = re.sub(r"[A-Z]+", lambda m: repl(m, "CAPS"), text)
text = re.sub(r"\d+", lambda m: repl(m, "NUMBER"), text)
return text
replacer("this is a 123 TEST 456", True)
# Log:
# Replacing TEST with CAPS...
# Replacing 123 with NUMBER...
# Replacing 456 with NUMBER...
然而,这对组不起作用——似乎re.sub
自动转义返回值repl
:
def replacer2(text, verbose=False):
def repl(matchobj, replacement):
if verbose:
print(f"Replacing {matchobj.group()} with {replacement}...")
return replacement
text = re.sub(r"([A-Z]+)(\d+)", lambda m: repl(m, r"\2\1"), text)
return text
replacer2("ABC123", verbose=True) # returns r"\2\1"
# Log:
# Replacing ABC123 with \2\1...
当然,可以编写一个更复杂的repl
函数来实际判断replacement
中的组,但在这一点上,对于仅仅让re.sub
报告替换的目标来说,这个解决方案似乎太复杂了.另一个可能的解决方案是只使用re.search
,报告它,然后使用re.sub
来进行替换,可能使用Pattern.sub
的变体来指定pos
和endpos
,以节省sub
函数不必再次搜索整个字符串.当然有比这两种 Select 更好的方法吗?