如何使用boost :: regex进行多次替换

kri*_*ofa 3 c++ regex boost

这是我的代码

// 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);
Run Code Online (Sandbox Code Playgroud)

然后用空字符串替换所有非ascii字符

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

我宁愿打一个电话来代替两个.

SCF*_*nch 6

这样做:

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;
Run Code Online (Sandbox Code Playgroud)

请参阅Boost-Extended Format String Syntax以及regex_replace文档末尾的示例.