I gave myself an hour to add multi-line search-and-replace support in my code.  It took 3, and C++11 std::regex_replace() gave me a hard crash with inline replacement.  The syntax can be annoying (for example, using double escape), so for reference, here’s a jumpstart.

Given:

using namespace std;
string str = "Lots of text to search\nacross lines";
string from = "text[\\s\\S]*lines";
string to = "rainbows";

Boost happily did the job:

#include 
 boost::regex reg;
 reg.assign(from);
 str = boost::regex_replace(str,reg,to,boost::match_default);

C++11 is even simpler, but it crashes with gcc 4.9.2 if you use the same string for source and target, like this:

#include 
 std::regex reg(from);
 str = std::regex_replace(str,reg,to);

You can fix that by using a swap string:

#include 
 regex reg(from);
 string newstr = regex_replace(str,reg,to);
 str = newstr;

But it isn’t working across lines, with this particular syntax, and I’ve seen others complain that they couldn’t get multiline syntax going.  I’ll stick with boost for now until this smooths out a little bit more.  Onwards.

 

Leave a Reply