问题描述
我正在遍历一系列正则表达式,并将其与文件中的行进行匹配,如下所示:
I'm looping through a series of regexes and matching it against lines in a file, like this:
for my $regex (@{$regexs_ref}) {
LINE: for (@rawfile) {
/@$regex/ && do {
# do something here
next LINE;
};
}
}
有没有办法让我知道我已经进行了多少次匹配(以便我可以相应地进行处理……)?
Is there a way for me to know how many matches I've got (so I can process it accordingly..)?
如果不是这样,那是错误的方法..?当然,除了遍历每个正则表达式外,我还可以为每个正则表达式编写一个配方.但是我不知道什么是最佳做法?
If not maybe this is the wrong approach..? Of course, instead of looping through every regex, I could just write one recipe for each regex. But I don't know what's the best practice?
推荐答案
如果您在列表上下文中进行匹配(即,基本上是分配给列表),则会在列表中获得所有匹配项和分组.然后,您可以仅在标量上下文中使用该列表来获取匹配数.
If you do your matching in list context (i.e., basically assigning to a list), you get all of your matches and groupings in a list. Then you can just use that list in scalar context to get the number of matches.
还是我误解了这个问题?
Or am I misunderstanding the question?
示例:
my @list = /$my_regex/g;
if (@list)
{
# do stuff
print "Number of matches: " . scalar @list . "\n";
}
这篇关于Perl正则表达式:如何知道匹配数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!