C++ regex with char and wchar_t?

丶灬走出姿态 提交于 2019-12-01 21:22:54

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.

user3230245

you can use another function to overload the function:

    std::wstring replaceSubstring(const wchar_t* find, const wchar_t* asciiChar, const wchar_t* replace)
    {
        std::wstring const text(str);
        std::wregex const reg(find);
        std::wstring const newStr = std::wregex_replace(text, reg, replace);
        return newStr;
    }
hyun

You can use template for this, like below,

template<typename CharT>
const CharT* replaceSubstring(const CharT* find, const CharT* str, const CharT* replace);

template<> const char* replaceSubstring<char>(const char* find, const char* str, const char* replace) 
{
    std::string const text(str);
    std::regex const reg(find);

    std::string swap_str(replace);

    return std::regex_replace(text, reg, swap_str).c_str();
}

template<> const wchar_t* replaceSubstring<wchar_t>(const wchar_t* find, const wchar_t* str, const wchar_t* replace) 
{   
    std::wstring const text(str);
    std::wregex const reg(find);

    std::wstring swap_str(replace);

    return std::regex_replace(text, reg, swap_str).c_str();
}

Also, overloading can be an other option.

You may get good advice from below link.

Is it possible to have a C++ method accept either const char* and const wchar_t* as a parameter without overloading the method?

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