Search code examples
c++boostboost-xpressive

Garbage characters after regex_replace


I am using boost xpressive regex_replace . After the replace I get garbage characters at the end of the string

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

Solution

  • After reserve string strOut has still 0 elements. So strOut.begin() == strOut.end() is true, and it points to nothing. If you want to use output iterator to write data in regex_replace, it must point to memory with enough room to store all data. You can fix it by calling resize instead of reserve.

    Another solution is to employ back_inserter to do this job (operator= on this iterator push data into string), then it is unnecessary, and the code looks like:

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