C++ regex with char and wchar_t?

fxfuture picture fxfuture · May 13, 2014 · Viewed 7.1k times · Source

I have a const char and a const wchar_t. My function below works with the char. What's the simplest/most efficient way to write a function that can easily handle both char and wchar_t?

    const char* asciiChar = "this is an ascii string";
    const wchar_t* unicodeChar = L"this is a unicode string";

    std::string replaceSubstring(const char* find, const char* asciiChar, const char* replace)
    {
        std::string const text(str);
        std::regex const reg(find);
        std::string const newStr = std::regex_replace(text, reg, replace);
        return newStr;
    }

Answer

zneak picture zneak · May 13, 2014

For this reason exactly, regex is a typedef of basic_regex<char>, much like string is a typedef of basic_string<char>. Knowing this, you can get away with a single template:

template<typename CharType>
std::basic_string<CharType>
  replaceSubstring(const CharType* find, const CharType* str, const CharType* rep)
{
    std::basic_string<CharType> text(str);
    std::basic_regex<CharType> reg(find);
    return std::regex_replace(text, reg, rep);
}

This correctly handles both char pointers and wchar_t pointers, and returns the correct type of string. You may want to accept const std::basic_string<CharType>& parameters instead, too.