Understanding c++ regex by a simple example

From here

    Returns whether **some** sub-sequence in the target sequence (the subject) 
    matches the regular expression rgx (the pattern). The target sequence is 
    either s or the character sequence between first and last, depending on 
    the version used.

So regex_search will search for anything in the input string that matches the regex. The whole string doesnt have to match, just part of it.

However, if you were to use regex_match, then the entire string must match.


You still get the entire match but the entire match does not fit the entire string it fits the entire regex.

For example consider this:

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

int main()
{
    std::string str("1231");
    std::regex r("^(\\d)\\d"); // entire match will be 2 numbers

    std::smatch m;
    std::regex_search(str, m, r);

    for(auto v: m)
        std::cout << v << std::endl;
}

Output:

12
1

The entire match (first sub_match) is what the entire regex matches against (part of the string).

The second sub_match is the first (and only) capture group

Looking at your original regex

std::regex r("^(\\d)");
              |----| <- entire expression (sub_match #0)

std::regex r("^(\\d)");
               |---| <- first capture group (sub_match #1)

That is where the two sub_matches come from.

Tags:

C++

Regex