有了这个问题的答案,我就能够创建一个函数,该函数使用regex来查找和替换与char和wchar_t一起工作的字符串
template<typename CharT>
basic_string<CharT> replaceString(const CharT* find, const CharT* str, const CharT* repl)
{
basic_string<CharT> text(str);
basic_regex<CharT> reg(find);
return regex_replace(text, reg, repl);
}
我一直试图实现与我的功能相同,以计算匹配的数量,但我不能弄清楚。目前我能做到的唯一方法是通过重载,但我想写一个函数来处理它。
int countMatches(const char* find, const char* str)
{
string text(str);
regex reg(find);
ptrdiff_t cnt = (distance(sregex_iterator(text.begin(), text.end(), reg), sregex_iterator()));
return (int) cnt;
}
int countMatches(const wchar_t* find, const wchar_t* str)
{
wstring text(str);
wregex reg(find);
ptrdiff_t cnt = (distance(wsregex_iterator(text.begin(), text.end(), reg), wsregex_iterator()));
return (int) cnt;
}
std::regex_iterator也是一个类模板
template<typename CharT>
std::size_t countMatches(const CharT* find, const CharT* str)
{
std::basic_string<CharT> text(str);
std::basic_regex<CharT> reg(find);
typedef typename std::basic_string<CharT>::iterator iter_t;
return distance(std::regex_iterator<iter_t>(text.begin(), text.end(), reg),
std::regex_iterator<iter_t>());
}