C++ regex_match not working

The problem is that std::regex_match must match the entire string but you are trying to match only part of it.

You need to either use std::regex_search or alter your regular expression to match all three parts at once:

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

const auto test =
{
      "foo.bar = 15"
    , "baz.asd = 13"
    , "ddd.dgh = 66"
};

int main()
{
    const std::regex r(R"~(([^.]+)\.([^\s]+)[^0-9]+(\d+))~");
    //                     (  1  )  (   2  )       ( 3 ) <- capture groups

    std::cmatch m;

    for(const auto& line: test)
    {
        if(std::regex_match(line, m, r))
        {
            // m.str(0) is the entire matched string
            // m.str(1) is the 1st capture group
            // etc...
            std::cout << "a = " << m.str(1) << '\n';
            std::cout << "b = " << m.str(2) << '\n';
            std::cout << "c = " << m.str(3) << '\n';
            std::cout << '\n';
        }
    }
}

Regular expression: https://regex101.com/r/kB2cX3/2

Output:

a = foo
b = bar
c = 15

a = baz
b = asd
c = 13

a = ddd
b = dgh
c = 66

Leave a Comment