代码之家  ›  专栏  ›  技术社区  ›  Gerald

如何转义用于Boost正则表达式的字符串

  •  27
  • Gerald  · 技术社区  · 16 年前

    我正在研究正则表达式,我正在使用Boost正则表达式库。

    我需要使用包含特定URL的正则表达式,它会阻塞,因为显然URL中有一些字符是为正则表达式保留的,需要转义。

    Boost库中是否有任何函数或方法可以为这种用法转义字符串?我知道在大多数其他正则表达式实现中都有这样的方法,但我在Boost中没有看到。

    4 回复  |  直到 16 年前
        1
  •  40
  •   LogicStuff    9 年前
    . ^ $ | ( ) [ ] { } * + ? \
    

    讽刺的是,您可以使用正则表达式来转义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);
    

    (国旗) 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);
    
        2
  •  14
  •   nhahtdh Pankaj Wadhwa    11 年前

    使用来自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;
    }
    

    std::string / boost::regex 而不是 std::wstring boost::wregex .

        3
  •  4
  •   Roman    13 年前

    boost::xpressive :

    const boost::xpressive::sregex re_escape_text = boost::xpressive::sregex::compile("([\\^\\.\\$\\|\\(\\)\\[\\]\\*\\+\\?\\/\\\\])");
    
    std::string regex_escape(std::string text){
        text = boost::xpressive::regex_replace( text, re_escape_text, std::string("\\$1") );
        return text;
    }
    
        4
  •  1
  •   Emile Cormier    8 年前

    在C++11中,可以使用 原始字符串文本 要避免转义正则表达式字符串,请执行以下操作:

    std::string myRegex = R"(something\.com)";

    看见 http://en.cppreference.com/w/cpp/language/string_literal