Home > Blockchain >  How to convert hex color string to RGB using regex in C
How to convert hex color string to RGB using regex in C

Time:11-30

How to convert the hex color string to RGB using regex?

I am using the regex but it is not working. I am not familiar with regex. Is it the correct way?

Below is the sample code:

int main()
{
    std::string l_strHexValue = "#FF0000";

    std::regex pattern("#?([0-9a-fA-F]{2}){3}");

    std::smatch match;
    if (std::regex_match(l_strHexValue, match, pattern))
    {
        auto r = (uint8_t)std::stoi(match[1].str(), nullptr, 16);
        auto g = (uint8_t)std::stoi(match[2].str(), nullptr, 16);
        auto b = (uint8_t)std::stoi(match[3].str(), nullptr, 16);
    }

    return 0;
}

CodePudding user response:

You can use

std::regex pattern("#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})");

Here, the FF, 00 and 00 are captured into a separate group.

Or, you can use a bit different approach.

std::string l_strHexValue = "#FF0000";
std::regex pattern("#([0-9a-fA-F]{6})");
std::smatch match;
if (std::regex_match(l_strHexValue, match, pattern))
{
    int r, g, b;
    sscanf(match.str(1).c_str(), "%2x%2x%2x", &r, &g, &b);
    std::cout << "R: " << r << ", G: " << g << ", B: " << b << "\n";
}
// => R: 255, G: 0, B: 0

See the C demo.

  • Related