Question

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;
    }
Était-ce utile?

La solution

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>());
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top