Using Boost Spirit to parse a text file while skipping large parts of it

廉价感情. 提交于 2019-12-05 21:40:32

You can just

omit [ eol >> *char_ - ("\nlabel A:") ] >> eol

Example: Live On Coliru

There's also the seek[] directive in the repository. The following is equivalent to the above:

 repo::seek [ eol >> &lit("int main") ] 

Here's a sample that parses your original sample:

*repo::seek [ eol >> "label" >> char_("A-Z") >> ':' >> int_ ],

This will parse into std::vector<std::pair<char, int> > without anything else.

On Coliru Too:

#if 0
<lots of text not including "label A" or "label B">    
label A: 34
<lots of text not including "label A" or "label B">
label B: 45
<lots of text not including "label A" or "label B">
...
#endif
#include <boost/fusion/adapted/std_pair.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/repository/include/qi_seek.hpp>
#include <fstream>

namespace qi   = boost::spirit::qi;
namespace repo = boost::spirit::repository::qi;

int main()
{
    std::ifstream ifs("main.cpp");
    ifs >> std::noskipws;

    boost::spirit::istream_iterator f(ifs), l;

    std::vector<std::pair<char, int> > parsed;
    using namespace qi;
    bool ok = phrase_parse(
            f, l, 
            *repo::seek [ eol >> "label" >> char_("A-Z") >> ':' >> int_ ],
            blank,
            parsed
        );

    if (ok)
    {
        std::cout << "Found:\n";
        for (auto& p : parsed)
            std::cout << "'" << p.first << "' has value " << p.second << "\n";
    }
    else
        std::cout << "Fail at: '" << std::string(f,l) << "'\n";
}

Notes:

Output is

Found:
'A' has value 34
'B' has value 45
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!