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

后端 未结 8 1364
悲哀的现实
悲哀的现实 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:55

    You can find overlapping matches by using a noncapturing subpattern:

    def count_overlapping(pattern, string):
        return len(re.findall("(?=%s)" % pattern, string))
    
    0 讨论(0)
  • 2020-11-27 06:56
    import re
    print len(re.findall(r'ab',u'ababababa'))
    
    0 讨论(0)
提交回复
热议问题