如何转义字符串以在Boost Regex中使用

Ger*_*ald 29 c++ regex boost escaping

我只是把我的头脑放在正则表达式上,而我正在使用Boost Regex库.

我需要使用包含特定URL的正则表达式,并且它会窒息,因为显然URL中有为正则表达式保留并且需要进行转义的字符.

Boost库中是否有任何函数或方法来转义字符串以进行此类用法?我知道在大多数其他正则表达式实现中都有这样的方法,但我没有在Boost中看到一个.

或者,是否有需要转义的所有字符的列表?

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)

  • 它很接近,只需要在代表的末尾添加一个"&",它就可以了.谢谢. (7认同)

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.