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

使美元和插入符号仅在字符串的开头/结尾匹配,而不是在嵌入换行符之前/之后匹配

  •  0
  • Enlico  · 技术社区  · 4 年前

    输出后的这段小代码

    <hello>
    <world>
    

    证明这一点 ^ $ 也在之前和之后匹配 \n 分别。我怎样才能改变这种行为,让它们只在字符串的开头和结尾匹配?(在这种情况下,示例中没有匹配项 str 输入。)

    #include <boost/regex.hpp>
    #include <iostream>
    int main() {
        std::string tokenRegex = "^[^\n\r]+$";
        std::string str = "hello\nworld";
        boost::sregex_iterator rit{std::begin(str), std::end(str), boost::regex{tokenRegex}};
        boost::sregex_iterator end;
    
        while (rit != end) {
            std::cout << '<' << rit->str() << '>' << '\n';
            ++rit;
        }
    }
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   Stack Exchange Supports Israel    4 年前

    你需要使用 match_single_line flag :

    boost::sregex_iterator rit{
        std::begin(str),
        std::end(str),
        boost::regex{tokenRegex},
        boost::match_single_line // <-- here
    };
    

    这是一个匹配标志——您可以在匹配(或构造匹配的迭代器)时指定它,而不是在编译正则表达式时指定它。