I want to list all matching groups in the input. For example, I want to print all browsers I care about in a User-Agent HTTP header. One match is enough. Is there a way to get rid of the inner for loop in the code below. I looked in the boost/regex/sub_match.hpp and I have no ideas.
#include <string>
#include <iostream>
#include <boost/regex.hpp> // Boost 1.59, no C++14 for me
enum BrowserType
{
FIREFOX = 0 ,
CHROME,
SAFARI,
OPERA,
IE,
EDGE,
OTHER,
};
const boost::regex BROWSERS_REGEX("(Firefox)|(Chrome)|(Safari)|(Opera)|(MSIE)|(Edge)|(Trident)");
int main()
{
// I expect two matches here CHROME and SAFARI
std::string input("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36 Chrome/62.0.3202.94");
boost::sregex_iterator res(input.begin(), input.end(), BROWSERS_REGEX);
boost::sregex_iterator end;
for(; res != end; ++res)
{
// elude copy here ?
boost::smatch what = *res;
// Can I know the index of the matching group w/o 'for'?
for (int type = 0;type < OTHER;type++)
{
int groupIndex = type+1;
if (what[groupIndex].matched)
std::cout << (BrowserType)type << ",";
}
std::cout << "\n";
}
return 0;
}
Important update. The strstr() based code is the fastest approach for strings shorter than 1K bytes
const char *input("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36 Chrome/62.0.3202.94");
const char *browsers[OTHER+1] = {"Firefox", "Chrome", "Safari", "Opera", "MSIE", "Edge", "Trident"};
int i = 0;
for (const char **browser = &browsers[0];browser <= &browsers[OTHER];browser++, i++)
{
if (strstr(input, *browser))
{
groupindex = i;
}
}