C++ regex with char and wchar_t?

后端 未结 3 689
余生分开走
余生分开走 2021-01-21 07:23

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 an

相关标签:
3条回答
  • 2021-01-21 07:26

    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;
        }
    
    0 讨论(0)
  • 2021-01-21 07:27

    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?

    0 讨论(0)
  • 2021-01-21 07:32

    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.

    0 讨论(0)
提交回复
热议问题