2017-08-10 29 views
1

我想在同一行中解析宏。 所以我在地圖中定義的宏:使用std :: regex_search解析同一行中的幾個宏

map<string, string> collection; 
collection["ComputerName"] = "Train-Alpha"; 
collection["State"] = "Unloaded"; 

宏符號是$(宏名),所以輸入行的樣子:

string line = "Running on $(ComputerName) while $(State)"; 

而且我用這個正則表達式:

regex expression("\\$\\(([^}]+)\\)"); 

但我下面的代碼考慮'最大'的子模式,而不是最小的:

#include <iostream> 
#include <regex> 
#include <map> 
#include <boost/algorithm/string.hpp> 

using namespace std; 

void main() 
{ 
    string line = "Running on $(StationName) while $(State)"; 
    map<string, string> collection; 
    collection["Station"] = "Train-Alpha"; 
    collection["State"] = "unloaded"; 
    regex pattern("\\($\\([^}]+\\))"); 
    smatch match; 

    while (regex_search(line, match, pattern)) 
    { 
     auto variableName = match[1].str(); 
     auto it = collection.find(variableName); 
     if (it != end(collection)) 
     { 
      auto keyword = "$(" + variableName + ")"; 
      auto value = it->second; 
      boost::replace_all(line, keyword, value); 
     } 
     else 
     { 
      break; 
     } 
    } 
    cout << line << endl; 
} 
+1

如果宏名可能嵌套,正則表達式不足:'「th是行$(has-a - $(nested-macro))「'。 –

回答

1

你在你的代碼中的一些錯誤:

  1. 第一映射值應改爲:

    collection["Station"] = "Train-Alpha"; 
    

    通過

    collection["StationName"] = "Train-Alpha"; 
    
  2. 正則表達式也應該改變:

    regex pattern("\\($\\([^}]+\\))"); 
    

    通過

    regex pattern("\\$\\(([^)]+)\\)"); 
    

    或者你也可以使用一個Raw string literal避免逃避反斜槓(或任何字符):

    regex pattern(R"(\$\(([^)]+)\))"); 
    

See a slightly modified working version on Ideone.