Number of regex matches

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

    If you always need to know the length, and you just need the content of the match rather than the other info, you might as well use re.findall. Otherwise, if you only need the length sometimes, you can use e.g.

    matches = re.finditer(...)
    ...
    matches = tuple(matches)
    

    to store the iteration of the matches in a reusable tuple. Then just do len(matches).

    Another option, if you just need to know the total count after doing whatever with the match objects, is to use

    matches = enumerate(re.finditer(...))
    

    which will return an (index, match) pair for each of the original matches. So then you can just store the first element of each tuple in some variable.

    But if you need the length first of all, and you need match objects as opposed to just the strings, you should just do

    matches = tuple(re.finditer(...))
    

提交回复
热议问题