How to do multiple replacements with boost :: regex

This is my code.

// replace all new lines with string "nl"
std::string s = "Stack\nover\rflowâ€";
boost::regex expr1("(\\n)|(\\r)");
std::string fmt("nl");
std::string s2 = boost::regex_replace(s, expr, fmt);

Then replace all non-ascii characters with an empty string

boost::regex expr2("([^\x20-\x7E])")
std::string fmt2("");
std::cout << boost::regex_replace(s2, expr2, fmt2) << std::endl;

I would rather replace one instead of two.

+3
source share
1 answer

This will be done:

std::string s = "Stack\nover\rflowâ€";
boost::regex expr("(\\n)|(\\r)|([^\x20-\x7E])");
std::string fmt("(?1nl)(?2nl)"); // Omitted the (?3) as a no-op
std::string s2 = boost::regex_replace(s, expr, fmt, boost::match_default | boost::format_all);
std::cout << s2 << std::endl;

See the syntax for the extended Boost format string and the example at the end of the document for regex_replace.

+6
source

All Articles