2016-08-18 51 views
0

我正在尋找從C++程序中的簡單字符串中提取RGB顏色,但它返回我0匹配!但是,我測試了http://regexr.com/的正則表達式,這似乎是正確的...那麼,怎麼了?std :: regex_match找不到我的字符串格式的RGB顏色

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

回答

1

std::regex_match匹配整個字符串,而不是子字符串。要提取所有子字符串,請參見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'; 
    } 
} 

輸出:

R: 225 
G: 85 
B: 62 

R: 129 
G: 89 
B: 52 

R: 12 
G: 95 
B: 78