Skip to content

Instantly share code, notes, and snippets.

@sonulohani
Created February 8, 2020 14:30
Show Gist options
  • Save sonulohani/f24915a5a44326164796decc3045f475 to your computer and use it in GitHub Desktop.
Save sonulohani/f24915a5a44326164796decc3045f475 to your computer and use it in GitHub Desktop.
C++: Parses curly braces values
#include <iostream>
#include <regex>
#include <string>
#include <vector>
#include <sstream>
#include <map>
std::vector<std::string> split(const std::string& s, char delimiter)
{
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(s);
while (std::getline(tokenStream, token, delimiter))
{
tokens.push_back(token);
}
return tokens;
}
int main()
{
std::string sentence{ "Something is hello {foo=6,bar=5}" };
std::regex within_curly_brace_regex(R"(\{([^}]+)\})");
std::smatch matched_value;
std::map<std::string, std::string> variable_to_value;
if (std::regex_search(sentence, matched_value, within_curly_brace_regex)) {
auto curly_value = matched_value[1];
auto split_variable_with_value = split(curly_value, ',');
for (const auto& variable_with_value : split_variable_with_value)
{
auto splitValues = split(variable_with_value, '=');
if (splitValues.size() == 2U)
{
variable_to_value.insert(std::pair<std::string, std::string>(splitValues[0], splitValues[1]));
}
}
}
for (const auto& variable_with_value : variable_to_value)
{
std::cout << variable_with_value.first << " " << variable_with_value.second << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment