0

I am trying to parse numbers separated with dots and get each number as sepate string. That is my sample program:

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

int main(int argc, char* argv[])
{
    try
    {
        std::string data("123.321.456.654");
        std::regex reg(R"(([0-9]+)\.(\1)\.(\1)\.(\1))");
        std::smatch m;
        if (std::regex_match(data, m, reg))
        {
            std::cout << m.size() << std::endl;
            //std::cout << m[0].str() << std::endl;
            std::cout << m[1].str() << std::endl;
            std::cout << m[2].str() << std::endl;
            std::cout << m[3].str() << std::endl;
            std::cout << m[4].str() << std::endl;
        }
    }
    catch (const std::exception& e)
    {
        std::cerr << "Error occurred: " << e.what() << std::endl;
    }

    return EXIT_SUCCESS;
}

In this sample I am using three regex:

works:

std::regex reg(R"((\d+)\.(\d+)\.(\d+)\.(\d+))");

works:

std::regex reg(R"(([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+))");

do not work at all:

std::regex reg(R"(([0-9]+)\.(\1)\.(\1)\.(\1))");

My question is why last regex is not working and where is error in syntax? Thanks.

Space Rabbit
  • 141
  • 2
  • 11

1 Answers1

1

The error is not in your syntax; it is in your logic.

Backreferences do not repeat a pattern; they match previously-matched text.

So, your pattern would match 123.123.123.123.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055