Question

I want to parse input like "start abc end" to extract "abc".

Here's my test code:

#include <boost/spirit/include/qi.hpp>
#include <ostream>

namespace qi = boost::spirit::qi;

int main(int argc, char* argv[])
{
    typedef std::string::const_iterator iterator;

    qi::rule<iterator, std::string(), qi::space_type> rule =
        "start" >>
        qi::lexeme[+qi::char_] >>
        "end";

    std::string input("start  abc end");
    auto iter = input.begin();
    std::string result;
    qi::phrase_parse(iter, input.end(), rule, qi::space, result);

    std::cout << "Result:   " << result   << std::endl;
}

The output is "Result: abc end".

Was it helpful?

Solution

Problem is, you expect your parser to stop at whitespace or the keyword "end". But your parser basically accepts any character after "start" keyword.

+char_

Above parser means: any character sequence longer than 1 (including whitespace).

Somehow you have to tell your parser to stop at whitespace or "end" keyword. For example below parser will accept characters until "end" keyword

+(char_ - lit("end"))

I suggest you to have a look at the list of parsers in spirit documentation. http://www.boost.org/doc/libs/1_55_0/libs/spirit/doc/html/spirit/qi/quick_reference/qi_parsers.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top