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;
}
如果宏名可能嵌套,正則表達式不足:'「th是行$(has-a - $(nested-macro))「'。 –