开发者

How to do multiple substitutions using boost:: regex

开发者 https://www.devze.com 2023-03-06 11:45 出处:网络
This is my code // replace all new lines with string \"nl\" std::string s = \"Stack\\nover\\rflowâ€\";

This is my code

// replace all new lines with string "nl"
std::string s = "Stack\nover\rflowâ€";
boost::regex expr1("(\\n)|(\\r)");
std::str开发者_如何学Pythoning fmt("nl");
std::string s2 = boost::regex_replace(s, expr, fmt);

Then replace all non-ascii characters with empty string

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

I would rather have one call to replace instead of two.


This will do it:

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 Boost-Extended Format String Syntax and the example at the end of the doc for regex_replace.

0

精彩评论

暂无评论...
验证码 换一张
取 消