Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of matches

Tags:

c++

regex

How do I count the number of matches using C++11's std::regex?

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

Expected output:

7

like image 907
Mateen Ulhaq Avatar asked Nov 27 '11 04:11

Mateen Ulhaq


People also ask

How do I count multiple matches in Excel?

You can use the COUNTIFS function in Excel to count cells in a single range with a single condition as well as in multiple ranges with multiple conditions. If the latter, only those cells that meet all of the specified conditions are counted.

Can a Countif () function count array?

Sum, SumProduct, Frequency, Linest, lookup functions, etc. take both range and array objects. To use countif, you have to use range in cells, defining the array in the formula on the go will not work.


1 Answers

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
like image 135
Jahid Avatar answered Oct 12 '22 11:10

Jahid