Home > Enterprise >  Why using regex_match I get a very big number of matches found?
Why using regex_match I get a very big number of matches found?

Time:01-16

I am new to regular expressions and faced the problem that I get a big number of matches (even more than symbols in the string), and moreover I am not able to print them. My code:

std::string s1 = "Do not trouble troubles until trouble troubles you";
std::smatch m1;
std::regex r1("(troubles?)");
std::regex_match(s1, m1, r1);

std::cout << std::boolalpha;
std::cout << "Matches found: " << m1.ready() << std::endl;
std::cout << "Matches count: " << m1.size() - 1 << std::endl;
for (int i = 1; i < m1.size(); i  )
{
   std::cout << m1.str(i) << std::endl;
}

And what I get is:

Matches found: true
Matches count: 4294967295

Where is my mistake?

CodePudding user response:

Your regex_match doesn't match anything so m1.size() is 0 which you then subtract 1 from. Since an unsigned type (size_t) is used, it'll wrap around and become the largest size_t possible.

A possible fix:

#include <iostream>
#include <regex>
#include <string>
int main() {
    std::string s1 = "Do not trouble troubles until trouble troubles you";
    std::smatch m1;
    std::regex r1("(troubles?)");   // regex_search instead of regex_match
    std::regex_search(s1, m1, r1);

    std::cout << std::boolalpha;
    std::cout << "Results ready: " << m1.ready() << std::endl;
    std::cout << "Matches count: " << m1.size() << std::endl;
    for (unsigned  i = 0; i < m1.size(); i  ) {
        std::cout << m1.str(i) << std::endl;
    }
}

Output:

Results ready: true
Matches count: 2
trouble
trouble

CodePudding user response:

Use std::match_results instead of std::smatch. std::smatch is just an instantiation of std::match_results.

It is much preferred though.

And you are subtract 1 from the loop.

  •  Tags:  
  • Related