How to escape a string for use in Boost Regex

前端 未结 4 1893
粉色の甜心
粉色の甜心 2020-11-27 17:21

I\'m just getting my head around regular expressions, and I\'m using the Boost Regex library.

I have a need to use a regex that includes a specific URL, and it choke

4条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 17:42

    Using code from Dav (+ a fix from comments), I created ASCII/Unicode function 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;
    }
    

    For ASCII version, use std::string/boost::regex instead of std::wstring/boost::wregex.

提交回复
热议问题