这是我的代码
// 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);
然后用空字符串替换所有非ascii字符
boost::regex expr2("([^\x20-\x7E])")
std::string fmt2("");
std::cout << boost::regex_replace(s2, expr2, fmt2) << std::endl;
我宁愿调用一次而不是调用两次。
最佳答案
这样做就可以了:
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;
参见 Boost-Extended Format String Syntax和 the example在 regex_replace 的文档末尾。
关于c++ - 如何使用 boost::regex 进行多次替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6005821/