C++ 使用std::regex_search解析同一行中的多个宏

C++ 使用std::regex_search解析同一行中的多个宏,c++,stl,C++,Stl,我想在同一行中解析宏。 因此,我在映射中定义宏: map<string, string> collection; collection["ComputerName"] = "Train-Alpha"; collection["State"] = "Unloaded"; 我使用这个正则表达式: regex expression("\\$\\(([^}]+)\\)"); 但下面的代码考虑了“最大”子模式,而不是最小的: #include <iostream> #inclu

我想在同一行中解析宏。 因此,我在映射中定义宏:

map<string, string> collection;
collection["ComputerName"] = "Train-Alpha";
collection["State"] = "Unloaded";
我使用这个正则表达式:

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;
}
#包括
#包括
#包括
#包括
使用名称空间std;
void main()
{
string line=“在$(StationName)上运行,而$(State)”;
地图收集;
集合[“车站”]=“列车阿尔法”;
集合[“状态”]=“已卸载”;
正则表达式模式(“\\($\\([^}]+\\)”;
小比赛;
while(正则表达式搜索(线、匹配、模式))
{
自动变量名称=匹配[1]。str();
auto it=collection.find(variableName);
如果(它!=结束(收集))
{
自动关键字=“$”(“+variableName+”);
自动值=它->秒;
boost::全部替换(行、关键字、值);
}
其他的
{
打破
}
}

您的代码中可能有一些错误:

  • 应更改第一个映射值:

    collection["Station"] = "Train-Alpha";
    
    regex pattern("\\($\\([^}]+\\))");
    

  • 正则表达式也应更改为:

    collection["Station"] = "Train-Alpha";
    
    regex pattern("\\($\\([^}]+\\))");
    

    或者也可以使用避免转义反斜杠(或任何字符):



  • 如果宏名称可能是嵌套的,则正则表达式不足:
    “此行$(has-a-$(嵌套宏))”
    regex pattern("\\$\\(([^)]+)\\)");
    
    regex pattern(R"(\$\(([^)]+)\))");