regex_replace后的垃圾字符

Garbage characters after regex_replace

我正在使用 boost xpressive regex_replace。替换后我在字符串末尾得到垃圾字符

std::wstring wEsc(L"fxSSyrpng");
std::wstring wReplaceByText(L"tiff");
std::wstring searchText(L"fx");

wsregex regExp;
try
{
    regExp = wsregex::compile( searchText );
}
catch ( regex_error &/*error*/ )
{
    throw ;
}
catch (...)
{
    throw ;
}
std::wstring strOut;
strOut.reserve( wEsc.length() + wReplaceByText.length() );
std::wstring::iterator it = strOut.begin();
boost::xpressive::regex_replace( it, wEsc.begin() , wEsc.end(), regExp, 
wReplaceByText,   regex_constants::match_not_null  );

reserve 之后,字符串 strOut 仍然有 0 个元素。所以 strOut.begin() == strOut.end() 是真的,而 it 没有指向任何东西。如果要使用输出迭代器将数据写入regex_replaceit 必须指向有足够空间存储所有数据的内存。您可以通过调用 resize 而不是 reserve.

来修复它

另一种解决方案是使用back_inserter来完成这项工作(operator=在这个迭代器上将数据推送到string),那么it是不必要的,并且代码看起来像:

std::wstring strOut;
boost::xpressive::regex_replace( std::back_inserter(strOut), wEsc.begin() , wEsc.end(), regExp, 
wReplaceByText,   boost::xpressive::regex_constants::match_not_null  );