Amb*_*ber 39
. ^ $ | ( ) [ ] { } * + ? \
Run Code Online (Sandbox Code Playgroud)
具有讽刺意味的是,您可以使用正则表达式来转义URL,以便将其插入到正则表达式中.
const boost::regex esc("[.^$|()\\[\\]{}*+?\\\\]");
const std::string rep("\\\\&");
std::string result = regex_replace(url_to_escape, esc, rep,
boost::match_default | boost::format_sed);
Run Code Online (Sandbox Code Playgroud)
(该标志boost::format_sed指定使用sed的替换字符串格式.在sed中,转义&将输出与整个表达式匹配的任何内容)
或者,如果您对sed的替换字符串格式不满意,只需将标志更改为boost::format_perl,您可以使用熟悉$&的参考表达式匹配的任何内容.
const std::string rep("\\\\$&");
std::string result = regex_replace(url_to_escape, esc, rep,
boost::match_default | boost::format_perl);
Run Code Online (Sandbox Code Playgroud)
Nis*_*shi 14
使用Dav的代码(+注释中的修复),我创建了ASCII/Unicode函数regex_escape():
std::wstring regex_escape(const std::wstring& string_to_escape) {
static const boost::wregex re_boostRegexEscape( _T("[.^$|()\\[\\]{}*+?\\\\]") );
const std::wstring rep( _T("\\\\&") );
std::wstring result = regex_replace(string_to_escape, re_boostRegexEscape, rep, boost::match_default | boost::format_sed);
return result;
}
Run Code Online (Sandbox Code Playgroud)
对于ASCII版本,请使用std::string/ boost::regex而不是std::wstring/ boost::wregex.