您可以将函数传递给re.sub
作为替换值。这可以让你做这样的事情:(虽然一个简单的搜索然后子方法虽然更慢会更容易推理):
import re
class Counter(object):
def __init__(self, start=0):
self.value = start
def incr(self):
self.value += 1
book = """This is some long text
with the text 'Some RE' appearing twice:
Some RE see?
"""
def countRepl(replacement, counter):
def replacer(matchobject):
counter.incr()
return replacement
return replacer
counter = Counter(0)
print re.sub(r'Some RE', countRepl('Replaced with..', counter), book)
print counter.value
这会产生以下输出:
This is some long text
with the text 'Replaced with..' appearing twice:
Replaced with.. see?
2