【问题标题】:boost regex pattern syntax confusion提升正则表达式模式语法混淆
【发布时间】:2016-01-25 00:25:16
【问题描述】:

我正在使用 boost regex,但我对 boost regex 使用的语法感到困惑。如果我想使用模式 "bb" 来匹配字符串 "aabbcc",我必须将模式 "bb" 设置为 ".*bb.*" 以便匹配字符串。这是连线的,因为在 perl 中您不需要在“bb”的前面和末尾添加“.*”。我是否错过了关于 boost regex 的一些东西,或者这只是 boost regex 的味道?下面是我这个问题的简单源代码:

#include <boost/regex.hpp>
#include <iostream>
#include <string>
int main() {
    boost::regex regex_bb01("bb");
    boost::regex regex_bb02(".*bb");
    boost::regex regex_bb03("bb.*");
    boost::regex regex_bb04(".*bb.*");

    if(boost::regex_match("aabbcc", regex_bb01))
        std::cout<<"the regex_bb01 is matched\n";
    else
        std::cout<<"the regex_bb01 is Not matched\n";
    if(boost::regex_match("aabbcc", regex_bb02))
        std::cout<<"the regex_bb02 is matched\n";
    else
        std::cout<<"the regex_bb02 is Not matched\n";
    if(boost::regex_match("aabbcc", regex_bb03))
        std::cout<<"the regex_bb03 is matched\n";
    else
        std::cout<<"the regex_bb03 is Not matched\n";
    if(boost::regex_match("aabbcc", regex_bb04))
        std::cout<<"the regex_bb04 is matched\n";
    else
        std::cout<<"the regex_bb04 is Not matched\n";
}

结果如下所示:

[root@localhost BoostCase]# ./regex_test

regex_bb01 不匹配

regex_bb02 不匹配

regex_bb03 不匹配

regex_bb04 匹配

【问题讨论】:

    标签: c++ regex perl boost


    【解决方案1】:

    来自 boost 文档的函数 regex_match

    算法regex_match判断给定的正则表达式是否匹配由一对双向迭代器表示的给定字符序列的all,算法定义如下,该函数的主要用途是数据输入验证。

    如果你想使用 'bb' 来匹配,你需要使用 boost::regex_search 来代替

    【讨论】:

    • Python 对 matchsearch 做了同样的区分。除非您正在验证一个字符串(通常您可以信任您的输入,因为它是机器生成的),否则它就是您想要的 search。如果您需要验证整个字符串,添加行锚^$ 的开始和结束很容易
    猜你喜欢
    • 2023-03-08
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多