如何使用正则表达式删除std :: wstring中特定短语的所有实例?

jus*_*rxl 0 c++ regex string replace std

我试图遵循这个答案:https://stackoverflow.com/a/32435076/5484426,但对于std :: wstring.到目前为止,我有这个:

std::wstring str = L"hello hi hello hi hello hi";
std::wregex remove = L"hi";
Run Code Online (Sandbox Code Playgroud)

现在我想这样做:regex_replace(str,remove,""); 虽然看起来regex_replace不适用于wstring.如何删除此字符串的所有实例?

chr*_*ris 5

std::regex_replace当然适用于std::wstring和所有其他专业std::basic_string.但是,替换格式字符串的字符类型必须与正则表达式和输入字符串的字符类型匹配.这意味着您需要一个宽替换格式字符串:

std::regex_replace(str, remove, L"");
Run Code Online (Sandbox Code Playgroud)

除此之外,std::wregex获取a 的构造函数const wchar_t*是显式的,因此您的复制初始化将不起作用.此外,这个重载std::regex_replace返回一个新的字符串,替换完成而不是在适当的位置,这是值得注意的.

以下是考虑以下几点的示例:

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

str = std::regex_replace(str, remove, L"");
Run Code Online (Sandbox Code Playgroud)