计算匹配次数

Count number of matches

本文关键字:计算      更新时间:2023-10-16

如何使用c++ 11的std::regex计算匹配次数?

std::regex re("[^\s]+");
std::cout << re.matches("Harry Botter - The robot who lived.").count() << std::endl;
预期输出:

7

您可以使用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;

你可以这样做:

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);
}

使用例子:

std::cout << countMatchInRegex("Harry Botter - The robot who lived.", "[^\s]+");
输出:

7