簡體   English   中英

計算比賽次數

[英]Count number of matches

如何使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM