我在C ++程序中从一个简单的字符串中寻找提取RGB颜色,但它返回0匹配!但是,我在http://regexr.com/测试了正则表达式,看起来是正确的...那么有什么不对?
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);
答案 0 :(得分: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