[英]Count number of matches
How do I count the number of matches using C++11's std::regex
? 如何使用C ++ 11的std::regex
计算匹配数?
std::regex re("[^\\s]+");
std::cout << re.matches("Harry Botter - The robot who lived.").count() << std::endl;
Expected output: 预期产量:
7 7
You can use regex_iterator
to generate all of the matches, then use distance
to count them: 您可以使用regex_iterator
生成所有匹配项,然后使用distance
进行计数:
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;
You can use this: 您可以使用此:
int countMatchInRegex(std::string s, std::string re)
{
std::regex words_regex(re);
auto words_begin = std::sregex_iterator(
s.begin(), s.end(), words_regex);
auto words_end = std::sregex_iterator();
return std::distance(words_begin, words_end);
}
Example usage: 用法示例:
std::cout << countMatchInRegex("Harry Botter - The robot who lived.", "[^\\s]+");
Output: 输出:
7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.