I want to replace multiple matches of a Regex with different values from a map.
I have for example the following string #id#_#date#_#value#_additional_text
.
I now want to replace the parts #xxx#
with the corresponding values from a map. (The string could change so that I don't exactly know what kind of patterns are in there.
What I'm currently doing are the following steps:
- Use
std::sregex_token_iterator
to go through the string and store all patterns I found in astd::vector
. - Go through all the patterns in the
vector
and usestd::regex_replace
to replace them with the values from the map.
This is the code for the steps above:
int main() {
std::map<std::string, std::string> metadata{
{"value", "9"},
{"id", "1234"},
{"date", "1234"},
{"more", "abc"}};
std::vector<std::string> patterns{};
std::string input_data = "#id#_#date#_#value#_additional_text";
std::regex reg{R"(#([a-zA-Z]+)#)"};
const std::sregex_token_iterator end;
for (std::sregex_token_iterator iter{std::cbegin(input_data), std::cend(input_data), reg, 1}; iter != end; ++iter) {
std::cout << iter->str() << '\n';
patterns.push_back(iter->str());
}
for (const auto pattern : patterns) {
std::cout << pattern << '\n';
std::regex regex_pattern{"#" + pattern + "#"};
input_data = std::regex_replace(input_data, regex_pattern, metadata[pattern]);
std::cout << input_data << '\n';
}
std::cout << input_data << '\n';
}
My question now is, is there a better way to achieve this?
#xxx#
(and so might be replaced by next replacement). \$\endgroup\$