2013-02-21 57 views
0

我存儲在unordered_map從正則表達式匹配得到的結果。 std :: cout子匹配m [1] .str()和m [2] .str()正確顯示對鍵值。錯誤從boost :: unordered :: unordered_map使用std :: string鍵恢復值

雖然當我把它們存儲在一個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; 
} 

倉庫路徑是一個「變量」這個名字在配置文件。 std :: cout < < m [1] .str()完美顯示,但未在unordered_map中找到。 任何想法?

回答

2

最有可能的是,您在無序映射中放入的鍵包含空格(輸出時看不到),因此稍後沒有找到。

在你的正則表達式^(.+)\\s*=\\s*(.+)中,第一個(.+)會貪婪地匹配儘可能多的字符,包括前導和尾隨空格。它後面的\\s*將始終匹配一個空字符串。爲防止出現這種情況,您只能將(\\S+)用於非空白字符,或者使用非貪婪的(.+?)

順便說一下,while (!fs.eof())是錯誤的。改爲使用while (std::getline(fs, line)) {...}

+0

2雙眼睛顯然比一隻眼睛好。 2小時努力修復錯誤,我需要刷新我的正則表達式的知識,非常感謝:) – 2013-02-21 11:51:56

相關問題