dutt dutt - 2 months ago 9
Python Question

Number of regex matches

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 I've got, is it possible without looping through the iterator twice? (one to find out the count and then the real iteration)

Edit:
As requested, some code:

imageMatches = re.finditer("<img src\=\"(?P<path>[-/\w\.]+)\"", response[2])
<Here I need to get the number of matches>
for imageMatch in imageMatches:
doStuff


Everything works, I just need to get the number of matches before the loop.

Answer

If you know you will want all the matches, you could use the re.findall function. It will return a list of all the matches. Then you can just do len(result) for the number of matches.

Comments