How to use the regex_iterator
on data types of const char*/wchar_t*
?
From docs:
using cregex_iterator = regex_iterator<const char*>;
using wcregex_iterator = regex_iterator<const wchar_t*>;
using sregex_iterator = regex_iteratorstring::const_iterator;
using wsregex_iterator = regex_iteratorwstring::const_iterator;
Reproducible example:
#include <string>
#include <iostream>
#include <regex>
template <typename T>
auto RegexMatchAll(const T* str, const T* regex)
{
using iter = std::regex_iterator<T>;
std::basic_regex<T> re(regex);
auto words_begin = iter(str, (str std::wcslen(str)), re); // <--- how to iterate according to the data in this case?
auto words_end = iter();
std::vector<std::match_results<iter>> result;
for (iter i = words_begin; i != words_end; i) {
std::match_results<iter> m = *i;
result.emplace_back(m);
}
return result;
}
int main() {
auto matches = RegexMatchAll(L"10,20,30", LR"((\d ))");
}
CodePudding user response:
You have a few errors. Assuming you pass a const char*
or const wchar_t*
, T
will be char
or wchar_t
, so:
std::regex_iterator
expects an iterator type, which neitherchar
norwchar_t
are. You want to pass itconst T*
instead.*i
will yeild astd::match_results<const T*>
as well, so that's the type you should store in yourresult
vector.std::wcslen
is only good forT = wchar_t
, you need to usestd::strlen
whenT = char
. I would create an overloaded wrapper function that calls the appropriate standard library function.
Putting that all together, something like this should work:
std::size_t str_len(const char* s) { return std::strlen(s); }
std::size_t str_len(const wchar_t* s) { return std::wcslen(s); }
template <typename T>
auto RegexMatchAll(const T* str, const T* regex)
{
using iter = std::regex_iterator<const T*>;
std::basic_regex<T> re(regex);
auto words_begin = iter(str, str str_len(str), re);
auto words_end = iter();
return std::vector<std::match_results<const T*>>(words_begin, words_end);
}
Note: I also simplified the std::vector
construction to use its iterator pair constructor.