【发布时间】:2016-10-16 05:43:58
【问题描述】:
在将 gcc 从 4.8.5 版升级到 5.3.1 版之后,我想我 可以摆脱 boost 的正则表达式实现(boost 版本 1.54.0)和 使用 gcc 提供的那个(在 4.9 版之前它不适用于 gcc 据我所知)。然而,事实证明这是一个问题,因为这两个 实现的行为不同:
#include <regex>
#include <boost/regex.hpp>
#include <iostream>
#include <string>
int main() {
std::string s="\\needs_another_backslash";
std::string reg("^(\\\\)(needs)(.+)");
std::string rep("\\\\got$3");
std::regex sr(reg);
boost::regex br(reg);
std::cout<<"string before replacement:\n"<<s<<std::endl<<
"regular expression:\n"<<reg<<std::endl<<
"replacement string:\n"<<rep<<std::endl<<
"std::regex_replace:\n"<<std::regex_replace(s,sr,rep)<<std::endl<<
"boost::regex_replace:\n"<<boost::regex_replace(s,br,rep)<<std::endl;
return 0;
}
这给出了以下输出:
string before replacement:
\needs_another_backslash
regular expression:
^(\\)(needs)(.+)
replacement string:
\\got$3
std::regex_replace:
\\got_another_backslash
boost::regex_replace:
\got_another_backslash
似乎 boost 对替换字符串中的 '\' 进行了特殊处理 而 gcc 没有。由于 std::regex_replace 的替换字符串中反向引用的神奇字符是 '$' (作为示例证明,它也在 boost 中),我倾向于认为 gcc 是正确的。但是,在许多其他程序(例如 vim)中,它是 '\'。因此,boost 可能在特殊处理 '\' 方面有意义。那么谁是对的呢?
【问题讨论】:
-
我不明白
std::string rep("\\\\got$3");如何变成\\\\got$3输出(在第一部分中只显示变量的值)- 我希望\\got$3输出(就像reg被处理)。 -
@Ped7g 是的,你是对的。对不起。我不小心复制了程序的输出,它以正确的方式得到了它。我纠正它。谢谢
-
要在
boost中获得与std实现相同的行为,您可以使用标志format_literal例如boost::regex_replace(text, rgx, fmt, match_flag_type::format_literal)