计算 Perl 或 Ruby 中重叠的正则表达式匹配项 [英] Count overlapping regex matches in Perl OR Ruby
问题描述
这是对该问题的跟进.我了解到在 Python 中找到重叠的正则表达式匹配并不简单,因此决定进行额外的调查,看看 Perl 和 Ruby 如何胜任这项任务.
This is a follow-up to that question. I've learned that finding overlapping regex matches in Python is not straight-forward, so decided to do an additional inquiry to see how Perl and Ruby stand up to this task.
我想计算正则表达式与某个字符串的所有可能匹配项的数量.全部"我的意思是结果应该同时考虑重叠和非唯一匹配.以下是一些示例:
I'd like to count the number of all possible matches of a regex against a certain string. And by "all" I mean that the result should take into account both overlapping and non-unique matches. Here are some examples:
a.*k
应该在"akka"
中匹配两次"bbboob"
针对b.*o.*b
测试应该产生 6
a.*k
should be matched twice in"akka"
"bbboob"
tested againstb.*o.*b
should yield 6
作为参考,这里是 tchrist 建议的 Perl 单行程序 - 它输出正确的匹配项及其计数:
As a reference, here's a Perl one-liner suggested by tchrist - it outputs the correct matches and their count:
() = "bbboobb" =~ /(b.*o.*b)(?{push @all, $1})(*FAIL)/g; printf "got %d matches: %s\n", scalar(@all), "@all";
唯一的问题是它会为测试用例占用太多资源,而结果匹配计数达到数百万或更多的数量级.但我明白这是因为所有比赛都是先分组的,然后才计算.我正在寻找一种资源高效的解决方案,它只返回计数.
The only problem with this is that it eats up too much resources for test cases where the resulting match count is in the order of millions or more. But I understand it is due to the fact that all the matches are first groupped and only counted afterwards. I'm looking for a resource-efficient solution that only returns the count.
推荐答案
看起来 tchrist 已经尽力了工作.如果存储匹配项并在之后计算它们占用了太多资源,那么您可以更改嵌入正则表达式的代码以仅计算匹配项:
It looks like tchrist has done all the hard work. If storing the matches and counting them afterwards is eating too much resource, then you could just change the regex-embedded code to just count the matches:
my $count = 0;
"bbboobb" =~ /(b.*o.*b)(?{$count++})(*FAIL)/g;
print "got $count matches\n";
这篇关于计算 Perl 或 Ruby 中重叠的正则表达式匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!