Find out how many times a regex matches in a string in Python

后端 未结 8 1386
悲哀的现实
悲哀的现实 2020-11-27 06:09

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

8条回答
  •  粉色の甜心
    2020-11-27 06:45

    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
    

提交回复
热议问题