Ant0nin Ant0nin - 3 months ago 13
C++ Question

std::regex_match do not find my string-formatted RGB colors

I looking for extract RGB colors from a simple string in a C++ program, but it returns me 0 match! However, I tested the regular expression at http://regexr.com/ and it seems correct... So what's wrong ?

std::string line = "225,85,62 129,89,52 12,95,78";
std::regex regexRGB("([0-9]{1,3}),([0-9]{1,3}),([0-9]{1,3})");
std::smatch colors;
std::regex_match(line, colors, regexRGB);

Answer

std::regex_match matches a whole string, not substrings. To extract all substrings look at std::sregex_iterator.

#include <regex>
#include <string>
#include <iostream>

int main()
{
    std::string line = "225,85,62 129,89,52 12,95,78";

    std::regex regexRGB("([0-9]{1,3}),([0-9]{1,3}),([0-9]{1,3})");

    std::sregex_iterator itr(line.begin(), line.end(), regexRGB);
    std::sregex_iterator end;

    for(; itr != end; ++itr)
    {
        std::cout << "R: " << itr->str(1) << '\n'; // 1st capture group
        std::cout << "G: " << itr->str(2) << '\n'; // 2nd capture group
        std::cout << "B: " << itr->str(3) << '\n'; // 3rd capture group
        std::cout << '\n';
    }
}

Output:

R: 225
G: 85
B: 62

R: 129
G: 89
B: 52

R: 12
G: 95
B: 78
Comments