C++ count matches regex function that works with both char and wchar_t?

蓝咒 提交于 2019-12-20 04:04:59

问题


With the answer from this question I was able to create a function that uses regex to find and replace in strings that works with both char and 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);
    }

I've been trying to achieve the same with my function to count the number of matches but I can't figure it out. Currently the only way I can do it is by overloading but I want to write a single function that can handle it.

    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;
    }

回答1:


std::regex_iterator is a class template too

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>());
}


来源:https://stackoverflow.com/questions/23644729/c-count-matches-regex-function-that-works-with-both-char-and-wchar-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!