正则表达式匹配次数 [英] Number of regex matches
问题描述
我正在使用 re
模块中的 finditer
函数来匹配某些内容,并且一切正常.
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)
一些代码:
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.
推荐答案
如果您知道需要所有匹配项,您可以使用 re.findall
函数.它将返回所有匹配项的列表.然后你可以对匹配的数量做 len(result)
.
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.
这篇关于正则表达式匹配次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!