6
// Example program
#include <iostream>
#include <string>
#include <regex>
int main()
{
 std::string strr("1.0.0.0029.443");

    std::regex rgx("([0-9])");
    std::smatch match;

    if (std::regex_search(strr, match, rgx)) {
        for(int i=0;i<match.size();i++)
            std::cout << match[i] << std::endl;
    }
}

this program should write

1
0
0
0
0
2
9
4
4
3

but it writes

1
1

checked it here http://cpp.sh/ and on visual studio, both same results.

Why does it find only 2 matches and why are they same?


As I understand from answers here, regex search stops at first match and match variable holds the necessary (sub?)string value to continue(by repeating) for other matches. Also since it stops at first match, () charachters are used only for sub-matches within the result.

huseyin tugrul buyukisik
  • 11,469
  • 4
  • 45
  • 97

2 Answers2

12

Being called once, regex_search returns only the first match in the match variable. The collection in match comprises the match itself and capture groups if there are any.

In order to get all matches call regex_search in a loop:

while(regex_search(strr, match, rgx))
{
    std::cout << match[0] << std::endl;
    strr = match.suffix();
}

Note that in your case the first capture group is the same as the whole match so there is no need in the group and you may define the regex simply as [0-9] (without parentheses.)

Demo: https://ideone.com/pQ6IsO

Dmitry Egorov
  • 9,542
  • 3
  • 22
  • 40
1

Problems:

  1. Using if only gives you one match. You need to use a while loop to find all the matches. You need to search past the previous match in the next iteration of the loop.
  2. std::smatch::size() returns 1 + number of matches. See its documentation. std::smatch can contain sub-matches. To get the entire text, use match[0].

Here's an updated version of your program:

#include <iostream>
#include <string>
#include <regex>

int main()
{
   std::string strr("1.0.0.0029.443");

   std::regex rgx("([0-9])");
   std::smatch match;

   while (std::regex_search(strr, match, rgx)) {
      std::cout << match[0] << std::endl;
      strr = match.suffix();
   }
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270