To replace all the occurences of a pattern in a string we could use the function regex_replace.
In the example is interesting noting that we create the regex using a flag to specify that it should be case insensitive (regex::icase). Notice that we should remember to or the flag to specify that we are using the default perl sintax for regular expression (regex::perl).
Other point of interest is that the string specified as replacement could be built from the regex itself, using the "$n" sintax. And this is useful in this case, since we want to preserve the original capitalization.
#include <iostream>
#include <string>
#include "boost/regex.hpp"
using std::cout;
using std::endl;
using std::string;
using boost::regex;
using boost::regex_replace;
int r04()
{
regex reg("(Colo)(u)(r)", regex::icase|regex::perl);
string s = "Colour, colours, color, colourize";
cout << s << endl;
s = regex_replace(s, reg, "$1$3");
cout << s << endl;
}
No comments:
Post a Comment