提升精神和凤凰解析为std :: string

时间:2016-07-21 02:48:55

标签: c++ boost boost-spirit boost-phoenix

如何使用boost spirit和phoenix解析为std :: string?

例如,下面我成功地将1234解析为int,但是当我尝试解析为字符串时,解析失败。如果我用qi::alnum替换+qi::alnum,则解析成功,但字符串编号具有不需要的值" 4"。似乎qi :: alnum只匹配一个字符;如何解析多字符字母数字字符串?

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>

#include <iostream>
#include <string>

int main() {

    namespace qi = boost::spirit::qi;
    namespace phoenix = boost::phoenix;

    std::string s("--1234--");

    {
        int number = 0;
        bool success = qi::parse(s.begin(), s.end(),
              qi::lit("--") >> qi::int_[ phoenix::ref(number) = qi::_1 ] >> qi::lit("--")
            );
        std::cout << success << " qi::int_ parses: " << number << std::endl;
    }

    {
        std::string number;
        bool success = qi::parse(s.begin(), s.end(),
              qi::lit("--") >> qi::alnum[ phoenix::ref(number) = qi::_1 ] >> qi::lit("--")
            );
        std::cout << success << " qi::alpha parses: " << number << std::endl;
    }

    return 0;
}

1 个答案:

答案 0 :(得分:2)

使用qi::as_string,例如

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>

#include <iostream>
#include <string>

int main() {

    namespace qi = boost::spirit::qi;
    namespace phoenix = boost::phoenix;

    std::string s("--1234--");

    std::string number;
    bool success = qi::parse( s.begin(), s.end(),
        qi::lit("--")
        >> qi::as_string [ +qi::alnum ] [ phoenix::ref(number) = qi::_1 ]
        >> qi::lit("--"));
    std::cout << success << " qi::as_string parses: " << number << std::endl;

    return 0;
}