【问题标题】:boost spirit and phoenix parsing into a std::string提升精神和凤凰解析成 std​​::string
【发布时间】:2016-07-21 02:48:55
【问题描述】:

如何解析成带有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;
}

【问题讨论】:

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


    【解决方案1】:

    使用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;
    }
    
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多