Skip to content

Instantly share code, notes, and snippets.

@studiofuga
Last active February 13, 2016 11:37
Show Gist options
  • Save studiofuga/d680c214c015c1679eaf to your computer and use it in GitHub Desktop.
Save studiofuga/d680c214c015c1679eaf to your computer and use it in GitHub Desktop.
Parse Key/Value pairs with boost::regex
#ifndef PARSEKV_H
#define PARSEKV_H
#include <tuple>
#include <string>
#include <boost/regex.hpp>
// link against boost_regex (-lboost_regex)
std::tuple<std::string,std::string> parseKeyValue(std::string arg)
{
boost::smatch results;
// Legal chars for key: numbers, letters, minus, underscore, point and slash (at least one)
// Legal chars for value: any char
// NOTE: if NO space is allowed between key, searator(=) and value, use the following regex instead
//boost::regex r{ "([\\w\\-_\\.\\/]+)=(.*)"};
boost::regex r{ "([\\w\\-_\\.\\/]+)\\s*=\\s*(.*)"};
if (!boost::regex_match(arg, results, r)) {
return std::tuple<std::string, std::string>();
}
if (results.size() != 3) {
return std::tuple<std::string, std::string>();
}
return std::make_tuple<std::string,std::string>(results[1], results[2]);
};
#endif // PARSEKV_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment