通过this question的回答,我能够创建一个函数,使用正则表达式来查找和替换与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;
}
答案 0 :(得分:4)
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>());
}