Poperton
Poperton

Reputation: 1746

How to access regex search result inside std::sub_match?

std::smatch ipv4Match;
std::regex_match(ipv4, ipv4Match, ip);

if (ipv4Match.empty())
{
    return std::nullopt;
}
else
{
    if (!ipv4Match.empty())
    {
        uint8_t a, b, c, d;
        a = (uint8_t)(ipv4Match[0]);
        b = (uint8_t)(ipv4Match[1]);
        c = (uint8_t)(ipv4Match[2]);
        d = (uint8_t)(ipv4Match[3]);
   }
}

However it obviously not work. I've researched and when I access smatch using [], it returns a sub_match, which does not have public members unless the constructor.

How can I convert each part of the match of the ip address into a byte?

Most importantly, how can std::cout << ipv4Match[0] work if it cannot access the inner string inside the ipv4Match since it's a sub_match?

Upvotes: 1

Views: 175

Answers (1)

Jarod42
Jarod42

Reputation: 218108

Your issue is unrelated to regex, but string to int conversion.

You might use std::atoi/std::stoi:

uint8_t a = std::stoi(ipv4Match[1].str());
uint8_t b = std::stoi(ipv4Match[2].str());
uint8_t c = std::stoi(ipv4Match[3].str());
uint8_t d = std::stoi(ipv4Match[4].str());

Upvotes: 2

Related Questions