====== C - C++ Strings - Search for patterns in strings ======
===== regex.hpp =====
#pragma once
#include
#include
#include
// Return a list of the list of submatches of regex in input.
std::vector> getMatches(std::string input, std::string regex);
std::vector getFirstMatch(std::string content, std::string pattern);
----
===== regex.cpp =====
#include "regex.hpp"
#include
std::vector> getMatches(std::string content, std::string pattern)
{
std::vector> result;
std::regex regex(pattern);
std::for_each(std::sregex_iterator(content.begin(), content.end(), regex), std::sregex_iterator(), [&](std::smatch match)
{
std::vector subMatches;
for (std::string subMatch : match)
{
subMatches.emplace_back(subMatch);
}
result.emplace_back(subMatches);
});
return result;
}
std::vector getFirstMatch(std::string content, std::string pattern)
{
std::vector subMatches;
std::smatch match;
if (std::regex_search(content, match, std::regex(pattern)))
{
for (std::string subMatch : match)
{
subMatches.emplace_back(subMatch);
}
}
return subMatches;
}
----
===== References =====
https://en.cppreference.com/w/cpp/regex/regex_iterator
https://en.cppreference.com/w/cpp/regex/regex_search