Number of regex matches

前端 未结 6 1880
长情又很酷
长情又很酷 2020-12-05 03:49

I\'m using the finditer function in the re module to match some things and everything is working.

Now I need to find out how many matches

6条回答
  •  悲&欢浪女
    2020-12-05 04:21

    If you find you need to stick with finditer(), you can simply use a counter while you iterate through the iterator.

    Example:

    >>> from re import *
    >>> pattern = compile(r'.ython')
    >>> string = 'i like python jython and dython (whatever that is)'
    >>> iterator = finditer(pattern, string)
    >>> count = 0
    >>> for match in iterator:
            count +=1
    >>> count
    3
    

    If you need the features of finditer() (not matching to overlapping instances), use this method.

提交回复
热议问题