Created
October 29, 2019 22:24
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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