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

如何使用C++ Boost的RexEx迭代器()

  •  7
  • Youssef  · 技术社区  · 16 年前

    我使用Boost来匹配字符串中的子字符串。Io迭代结果,我需要使用 regex_iterator() .


    "Hello everybody this is a sentense
    Bla bla 14 .. yes 
    date 04/15/1986 
    "
    

    我想得到:

    "Hello" "everybody" "this" "is" "a" "sentense" "bla" "yes" "date"
    
    2 回复  |  直到 14 年前
        1
  •  9
  •   Éric Malenfant    16 年前

    如果您不理解的示例的唯一部分是回调,请考虑:

    std::for_each(m1, m2, &regex_callback);
    

    for (; m1 != m2; ++m1){
        class_index[(*m1)[5].str() + (*m1)[6].str()] = (*m1).position(5);
    }
    

    假设在您的例子中,您希望将所有匹配项存储在一个向量中,您将编写如下内容:

    //Warning, untested:
    boost::sregex_iterator m1(text.begin(), text.end(), expression);
    boost::sregex_iterator m2;
    std::vector<std::string> tokens;
    for (; m1 != m2; ++m1){
        tokens.push_back(m1->str()).
    }
    
        2
  •  1
  •   bua    16 年前

    再加上一些逻辑。 看看 boost::tokenizer

    前任:

    boost::char_separator<char> sep_1(" ");
    
    
    std::string msg_copy ("Hello everybody this is a sentense Bla bla 14 .. yes date 04/15/1986 ");
    boost::tokenizer< boost::char_separator<char> > tokens(msg_copy, sep_1);
    BOOST_FOREACH(std::string t, tokens)
    {
            // here you itterate t
    }
    

    您可以将任意多个特殊字符放入分隔符,例如:

    boost::char_separator<char> sep_1(" *^&%~/|");