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_replace中写入数据,it必须指向具有足够空间来存储所有数据的内存。您可以通过调用 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  );

最新更新