Is there a way that I can find out how many matches of a regex are in a string in Python? For example, if I have the string \"It actually happened when it acted out of
To avoid creating a list of matches one may also use re.sub with a callable as replacement. It will be called on each match, incrementing internal counter.
class Counter(object):
def __init__(self):
self.matched = 0
def __call__(self, matchobj):
self.matched += 1
counter = Counter()
re.sub(some_pattern, counter, text)
print counter.matched