计数匹配数 [英] Count number of matches
本文介绍了计数匹配数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何计算使用C ++ 11的 std :: regex
?匹配的数量
How do I count the number of matches using C++11's std::regex
?
// Returns the estimated number of words in s.
size_t nOfWords(std::string s)
{
std::regex re(".*?\s?");
return(regex_count(s, re));
}
std::cout << nOfWords("Harry Botter - The robot who lived.") << std::endl;
预期输出:
7
7
推荐答案
可以使用 regex_iterator
以生成所有的匹配,然后使用
distance
对它们进行计数:
You can use regex_iterator
to generate all of the matches, then use distance
to count them:
std::regex const expression("[^\\s]+");
std::string const text("Harry Botter - The robot who lived.");
std::ptrdiff_t const match_count(std::distance(
std::sregex_iterator(text.begin(), text.end(), expression),
std::sregex_iterator()));
std::cout << match_count << std::endl;
这篇关于计数匹配数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文