0

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  );
sameer karjatkar
  • 2,017
  • 4
  • 23
  • 43
  • 1
    You probably confused `reserve` with `resize`. After `reserve` this condition `strOut.begin() == strOut.end()` is true, so how do you want to write data by `it` ? You cannot, output iterator can give you the access to element which exists and modify it, but in your case `it` points to nothing - `strOut` is empty. – rafix07 Apr 11 '19 at 07:41
  • perfect ..thanks ..can u post it as answer, so I can accept – sameer karjatkar Apr 11 '19 at 08:41

1 Answers1

0

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  );
rafix07
  • 20,001
  • 3
  • 20
  • 33