How to escape a string for use in Boost Regex

前端 未结 4 1888
粉色の甜心
粉色の甜心 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:33

    . ^ $ | ( ) [ ] { } * + ? \
    

    Ironically, you could use a regex to escape your URL so that it can be inserted into a regex.

    const boost::regex esc("[.^$|()\\[\\]{}*+?\\\\]");
    const std::string rep("\\\\&");
    std::string result = regex_replace(url_to_escape, esc, rep,
                                       boost::match_default | boost::format_sed);
    

    (The flag boost::format_sed specifies to use the replacement string format of sed. In sed, an escape & will output whatever matched by the whole expression)

    Or if you are not comfortable with sed's replacement string format, just change the flag to boost::format_perl, and you can use the familiar $& to refer to whatever matched by the whole expression.

    const std::string rep("\\\\$&");
    std::string result = regex_replace(url_to_escape, esc, rep,
                                       boost::match_default | boost::format_perl);
    

提交回复
热议问题