1

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;
}
4
  • The regex must be std::regex pattern("#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})\\b"); Commented Nov 28, 2021 at 13:30
  • Please don't use C-style casting. Use static_cast<uint8_t>(...) instead. Commented Nov 28, 2021 at 13:37
  • 1
    Also, you don't really need regular expressions here (most of the time it's overkill), if you know the input string is in the correct format to begin with. Then use either substr() to get two digits at a time to convert. Or use arithmetic to convert digit by digit. Commented Nov 28, 2021 at 13:39
  • Why don't you use an online bytes to long conversion tool. Or an hex to long, then split to bytes Win32 is good macro RGB( ) Commented Nov 28, 2021 at 21:45

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.