Perl regex:如何知道匹配数
我循环遍历一系列正则表达式并将其与文件中的行进行匹配,如下所示:
for my $regex (@{$regexs_ref}) {
LINE: for (@rawfile) {
/@$regex/ && do {
# do something here
next LINE;
};
}
}
有没有办法让我知道我有多少匹配项(以便我可以相应地处理它......)?
如果不是,也许这是错误的方法..?当然,我可以为每个正则表达式编写一个配方,而不是循环遍历每个正则表达式。但我不知道最好的做法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您在列表上下文中进行匹配(即基本上分配给列表),您将在列表中获得所有匹配和分组。然后您可以在标量上下文中使用该列表来获取匹配项的数量。
或者我误解了这个问题?
例子:
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?
Example:
您需要自己跟踪这一点。这是一种方法:
You will need to keep track of that yourself. Here is one way to do it:
在 CA::Parser 的处理中与
/$CA::Regex::Parser{Kills}{all}/
的匹配相关联,您使用捕获$1
一直到$10< /code>,其余大多数使用较少。如果匹配数指的是捕获数(
$n
具有值的最高 n),则可以使用 Perl 的特殊@-< /code> 数组(强调已添加):
用法示例:
输出:
In CA::Parser's processing associated with matches for
/$CA::Regex::Parser{Kills}{all}/
, you're using captures$1
all the way through$10
, and most of the rest use fewer. If by the number of matches you mean the number of captures (the highest n for which$n
has a value), you could use Perl's special@-
array (emphasis added):Example usage:
Output:
下面的代码怎么样:
它按预期打印 9。
How about below code:
It prints 9 here as expected.