Number of regex matches

前端 未结 6 1855
长情又很酷
长情又很酷 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:23

    For those moments when you really want to avoid building lists:

    import re
    import operator
    from functools import reduce
    count = reduce(operator.add, (1 for _ in re.finditer(my_pattern, my_string))) 
    

    Sometimes you might need to operate on huge strings. This might help.

提交回复
热议问题