Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ regex with char and wchar_t?

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;
    }
like image 539
fxfuture Avatar asked Oct 26 '25 06:10

fxfuture


1 Answers

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.

like image 118
zneak Avatar answered Oct 28 '25 19:10

zneak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!