【问题标题】:Make dollar and caret only match at beginning/end of string, not before/after embedded newlines使美元和插入符号仅在字符串的开头/结尾匹配,而不是在嵌入换行符之前/之后
【发布时间】:2021-01-03 12:54:46
【问题描述】:

输出后的这段小代码

<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;
    }
}

【问题讨论】:

  • 不是重复的,链接的问题是询问 std::regex 而不是 boost::regex。我投票决定重新打开它。
  • 谢谢,不过答案可能包含在one of the answers 的一条评论中。明天上班时,我会检查\z 是否按照该评论中的说明工作。如果是这样,那么该评论就是答案,应在此处复制为实际答案。

标签: c++ regex c++11 boost multiline


【解决方案1】:

您需要使用match_single_line flag:

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

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

【讨论】:

    猜你喜欢
    • 2018-07-14
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    • 2020-07-25
    相关资源
    最近更新 更多