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;
}
std::regex pattern("#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})\\b");static_cast<uint8_t>(...)instead.substr()to get two digits at a time to convert. Or use arithmetic to convert digit by digit.