【问题标题】:How to do multiple substitutions using boost:: regex如何使用 boost:: regex 进行多次替换
【发布时间】:2011-05-15 01:02:53
【问题描述】:

这是我的代码

// 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;

我宁愿打一个电话来替换而不是两个。

【问题讨论】:

  • 我知道它不能直接回答您的问题,但我认为您应该保留两个单独的电话,因为这是两个单独的任务。
  • 以下回复解决了您的问题。如果您将其标记为正确,那就太好了。

标签: c++ regex boost


【解决方案1】:

这样就可以了:

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;

有关 regex_replace,请参阅文档末尾的 Boost-Extended Format String Syntax 和 the example。

【讨论】:

  • 你测试过这个吗?在我的系统上,这会返回意外结果。 Stack(?1nl)(?2nl)over(?1nl)(?2nl)flow(?1nl)(?2nl)(?1nl)(?2nl) Windows 7 VS 2008 Express
  • 糟糕。我忘记了启用 (?Ntext) 语法的 boost::format_all match_flag。我更正了代码并在 g++ 下对其进行了测试。对不起。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 2012-01-26
  • 1970-01-01
相关资源
最近更新 更多