justanotherxl
justanotherxl

Reputation: 319

How to use Regular Expressions to remove all instances of a specific phrase in an std::wstring?

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?

Upvotes: 0

Views: 1528

Answers (1)

Qaz
Qaz

Reputation: 61960

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"");

Upvotes: 5

Related Questions