I'm storing in an unordered_map the results I get from a regex match. std::cout the sub matches m[1].str() and m[2].str() shows the pair key-value correctly.
Although when I store them in an unordered_map I always get an exception reporting that the key wasn't found.This is the code:
boost::unordered::unordered_map<std::string, std::string>
loadConfigFile(std::string pathToConfFile) throw(std::string){
std::fstream fs;
fs.open(pathToConfFile.c_str());
if(!fs)
throw std::string("Cannot read config file.");
boost::unordered::unordered_map<std::string, std::string> variables;
while(!fs.eof())
{
std::string line;
std::getline(fs, line);
//std::cout << line << std::endl;
boost::regex e("^(.+)\\s*=\\s*(.+)");
boost::smatch m; //This creates a boost::match_results
if(boost::regex_match(line, m, e)){
std::cout << m[1].str() << " " << m[2].str() << std::endl;
variables[m[1].str()] = m[2].str();
}
}
std::cout << variables.at(std::string("DEPOT_PATH")) << std::endl; //Here I get the exception
return variables;
}
DEPOT_PATH is the name of a "variable" in a config file. std::cout << m[1].str() shows it perfectly, but not found in the unordered_map. Any ideas?
Most likely, the key you put in the unordered map contains whitespace (which you don't see when outputting it) and therefore is not found later.
In your regex ^(.+)\\s*=\\s*(.+)
, the first (.+)
will greedily match as many characters as possible, including leading and trailing whitespace. The \\s*
following it will always match an empty string. To prevent this, you can use (\\S+)
for non-whitespace only, or use a non-greedy (.+?)
.
By the way, while (!fs.eof())
is wrong. Use while (std::getline(fs, line)) {...}
instead.