Skip to content

Instantly share code, notes, and snippets.

@AntonioCS
Created October 29, 2019 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AntonioCS/7ee70aba3bac2b57843ab37da7584f31 to your computer and use it in GitHub Desktop.
Save AntonioCS/7ee70aba3bac2b57843ab37da7584f31 to your computer and use it in GitHub Desktop.
Using c++ regex to create a match all function which returns the matched element and the position
#include <iostream>
#include <string>
#include <vector>
#include <regex>
auto match_all(std::string input, const std::string& pattern) noexcept {
std::vector<std::pair<std::string, int>> matches{};
try {
const std::regex self_regex(pattern);//, std::regex_constants::ECMAScript | std::regex_constants::icase);
std::smatch m;
uint64_t positionFix{};
while (std::regex_search(input, m, self_regex)) {
matches.emplace_back(m.str(), positionFix + m.position());
input = m.suffix();
positionFix += m.position() + m.length();
}
}
catch (const std::regex_error& e) {
std::cout << "regex_error caught: " << e.what() << '\n';
}
return matches;
}
int main() {
const std::string test{"Hello {{ name }}{{ surname }} How are things with you?"};
auto result = match_all(test, "(\\{\\{|\\{%|\\{#(\\-|~)?)");
for (auto const& [match, position]: result) {
std::cout << "Match : " << match << " position: " << position << '\n';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment