0

I am trying to follow this answer: https://stackoverflow.com/a/32435076/5484426, but for std::wstring. So far, I have this:

std::wstring str = L"hello hi hello hi hello hi";
std::wregex remove = L"hi";

Now I want to do this: regex_replace(str,remove,""); It doesn't look like regex_replace works for wstring though. How do I remove all instances of this string?

Community
  • 1
  • 1
justanotherxl
  • 319
  • 1
  • 11

1 Answers1

5

std::regex_replace certainly works for std::wstring, and all other specializations of std::basic_string. However, the replacement format string's character type must match the character type of the regex and input string. This means you need a wide replacement format string:

std::regex_replace(str, remove, L"");

Apart from that, the constructor of std::wregex taking a const wchar_t* is explicit, so your copy-initialization will not work. Also, this overload of std::regex_replace returns a new string with the replacements done rather than doing them in place, which is something to be aware of.

Here is an example with these points considered:

std::wstring str = L"hello hi hello hi hello hi";
std::wregex remove{L"hi"};   

str = std::regex_replace(str, remove, L"");
chris
  • 60,560
  • 13
  • 143
  • 205