gpt4 book ai didi

c++ - 使用 std::regex_search 在同一行解析多个宏

转载 作者:行者123 更新时间:2023-11-30 05:10:36 27 4
gpt4 key购买 nike

我想在同一行中解析宏。所以我在 map 中定义宏:

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

宏符号是 $(MacroName) 所以输入行看起来像:

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. 应该更改第一个映射值:

    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.

关于c++ - 使用 std::regex_search 在同一行解析多个宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45603640/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com