您可以將函數傳遞給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
如果if語句沒有在該行上執行,那麼if語句會是什麼樣子? –
...'!='(不等於)是什麼?當然是==(等於)。 – kindall
它只是不會增加計數器,因爲'line'和'reg1'會相同。如果沒有匹配,'re.sub()'只返回原始字符串。 – Nate