我将正则表达式匹配得到的结果存储在unordered_map中。cout sub匹配m1.str(),m2.str()正确显示密钥-值对。
虽然当我将它们存储在unordered_map中时,我总是得到一个异常,报告关键字不是found.This,但代码是:
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是配置文件中“变量”的名称。cout << m1.str()完美地显示了它,但在unordered_map中找不到。有什么想法吗?
发布于 2013-02-21 19:28:46
最有可能的情况是,您放在无序映射中的键包含空白(在输出时看不到),因此以后找不到它。
在您的正则表达式^(.+)\\s*=\\s*(.+)中,第一个(.+)将贪婪地匹配尽可能多的字符,包括前导和尾随空格。它后面的\\s*始终匹配空字符串。为了防止出现这种情况,您可以只对非空格使用(\\S+),或者使用非贪婪的(.+?)。
顺便说一句,while (!fs.eof())错了。请改用while (std::getline(fs, line)) {...}。
https://stackoverflow.com/questions/15000959
复制相似问题