我正在尝试实现一种用于正则表达式匹配的字符串转义方法。
不幸的是,我发现编译器之间存在不一致性。使用GCC 7.1和Visual Studio 2015U3编译此代码(添加了boost实现以进行比较)会产生不同的结果:
#include <iostream>
#include <regex>
#include <string>
#include <boost/regex.hpp>
std::string regexEscape(const std::string& s)
{
return std::regex_replace(s, std::regex{ R"([\^\.\$\|\{\}\(\)\[\]\*\+\?\/\\])" }, std::string{ R"(\\\1&)" }, std::regex_constants::match_default | std::regex_constants::format_sed);
}
std::string boostRegexEscape(const std::string& s)
{
return boost::regex_replace(s, boost::regex{ R"([\^\.\$\|\{\}\(\)\[\]\*\+\?\/\\])" }, std::string{ R"(\\\1&)" }, boost::match_default | boost::format_sed);
}
int main()
{
std::string test{ R"(123.456^789$123\456|789*123+456(789)123?456)" };
std::cout << regexEscape(test) << '\n';
std::cout << boostRegexEscape(test) << '\n';
}
GCC:
123\\.456\\^789\\$123\\\456\\|789\\*123\\+456\\(789\\)123\\?456
123\.456\^789\$123\\456\|789\*123\+456\(789\)123\?456
MSVC:
123\.456\^789\$123\\456\|789\*123\+456\(789\)123\?456
123\.456\^789\$123\\456\|789\*123\+456\(789\)123\?456
这是预期行为吗?