简体   繁体   中英

How to convert hex color string to RGB using regex in C++

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;
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM