我在re模块中使用finditer-function来匹配某些东西,一切正常.
现在我需要找出我有多少匹配,是否可以在没有循环遍历迭代器两次的情况下?(一个找出计数,然后是真实的迭代)
编辑:根据要求,一些代码:
imageMatches = re.finditer("<img src\=\"(?P<path>[-/\w\.]+)\"", response[2])
# <Here I need to get the number of matches>
for imageMatch in imageMatches:
doStuff
Run Code Online (Sandbox Code Playgroud)
一切正常,我只需要在循环之前获得匹配的数量.
Jos*_*shD 85
如果您知道您将需要所有匹配项,则可以使用该re.findall
功能.它将返回所有匹配的列表.然后你可以做len(result)
的比赛数量.
如果您总是需要知道长度,并且您只需要匹配的内容而不是其他信息,那么您也可以使用re.findall
.否则,如果您有时只需要长度,可以使用例如
matches = re.finditer(...)
...
matches = tuple(matches)
Run Code Online (Sandbox Code Playgroud)
将匹配的迭代存储在可重用的元组中.然后就做len(matches)
.
另一种选择,如果您只需要知道对匹配对象做任何事后的总计数,就可以使用了
matches = enumerate(re.finditer(...))
Run Code Online (Sandbox Code Playgroud)
这将为(index, match)
每个原始比赛返回一对.那么你可以将每个元组的第一个元素存储在某个变量中.
但是如果你首先需要长度,并且你需要匹配对象而不仅仅是字符串,你应该这样做
matches = tuple(re.finditer(...))
Run Code Online (Sandbox Code Playgroud)
小智 8
#An example for counting matched groups
import re
pattern = re.compile(r'(\w+).(\d+).(\w+).(\w+)', re.IGNORECASE)
search_str = "My 11 Char String"
res = re.match(pattern, search_str)
print(len(res.groups())) # len = 4
print (res.group(1) ) #My
print (res.group(2) ) #11
print (res.group(3) ) #Char
print (res.group(4) ) #String
Run Code Online (Sandbox Code Playgroud)
如果您发现需要坚持使用finditer()
,则可以在遍历迭代器时简单地使用一个计数器。
例:
>>> 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
Run Code Online (Sandbox Code Playgroud)
如果您需要的功能finditer()
(不匹配重叠的实例),请使用此方法。
小智 5
我知道这有点旧,但是这是一个用于计算正则表达式模式的简洁函数。
def regex_cnt(string, pattern):
return len(re.findall(pattern, string))
string = 'abc123'
regex_cnt(string, '[0-9]')
Run Code Online (Sandbox Code Playgroud)