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

标签 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);

然后用空字符串替换所有非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 Syntaxthe example在 regex_replace 的文档末尾。

关于c++ - 如何使用 boost::regex 进行多次替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6005821/

相关文章:

regex - 使用 posix shell 测试字符串中的正则表达式

c++ - 如何在运行时加载 COM DLL

regex - 使用 Asp.Net Core 中间件将非 WWW 重定向到 WWW

r - 如何检索字符串中的所有数字并使用正则表达式将它们组合成一个数字?

boost - 如何使用 boost::program_options 解析逗号分隔值?

c++ - cout << Boost::posix_time 的奇怪行为

ios - 无法链接胖iOS静态库

c++ - 为什么在不需要时使用这么多宏

c++ - 如何在 Qt、GCD 风格的给定线程中执行仿函数或 lambda?

c++ - C++中的 bool 表达式(语法)解析器