2

是否可以使用 boost::spirit::qi 解析以下内容?

 A_B       --> (A, B)
 A_B_C     --> (A_B, C)
 A_B_C_D   --> (A_B_C, D)
 A_B_C_D_E --> (A_B_C_D, E)

我想生成规则,以便我可以匹配字符串中的最后一个 '_' 并在其上拆分字符串。

4

1 回答 1

3

这看起来像一个奇怪的语法,并且对于专门的功能来说是一个更好的工作(特别是因为源“令牌”在您的示例中实际上非常短)。

但是,事不宜迟,您可以使用 Spirit 执行以下操作:

name  = lexeme [ +(graph - '_') ]; // or just char_("ABCDEFG") if it's that simple
entry = lexeme [ raw [ +(name >> '_') ] >> name ];

再次,在http://liveworkspace.org/code/15d970571a61dd39faedc8b7231ef67d上查看代码

// #define BOOST_SPIRIT_DEBUG
#include <boost/fusion/adapted.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>
#include <map>

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

typedef std::map<std::string, std::string> pairs_t;

template <typename It, typename Skipper = qi::space_type>
    struct parser : qi::grammar<It, pairs_t(), Skipper>
{
    parser() : parser::base_type(start)
    {
        using namespace qi;

        name  = lexeme [ +(graph - '_') ]; // or just char_("ABCDEFG") if it's that simple
        entry = lexeme [ raw [ +(name >> '_') ] >> name ];
        start = *entry;
        BOOST_SPIRIT_DEBUG_NODE(name);
        BOOST_SPIRIT_DEBUG_NODE(entry);
        BOOST_SPIRIT_DEBUG_NODE(start);
    }

  private:
    qi::rule<It, std::string()> name;
    qi::rule<It, std::pair<std::string, std::string>(), Skipper> entry;
    qi::rule<It, pairs_t(), Skipper> start;
};

template <typename C, typename Skipper>
    bool doParse(const C& input, const Skipper& skipper)
{
    auto f(std::begin(input)), l(std::end(input));

    parser<decltype(f), Skipper> p;
    pairs_t data;

    try
    {
        bool ok = qi::phrase_parse(f,l,p,skipper,data);
        if (ok)   
        {
            std::cout << "parse success\n";
            std::cout << "data: " << karma::format_delimited(karma::auto_ % ';', ' ', data) << '\n';
        }
        else    std::cerr << "parse failed: '" << std::string(f,l) << "'\n";

        if (f!=l) std::cerr << "trailing unparsed: '" << std::string(f,l) << "'\n";
        return ok;
    } catch(const qi::expectation_failure<decltype(f)>& e)
    {
        std::string frag(e.first, e.last);
        std::cerr << e.what() << "'" << frag << "'\n";
    }

    return false;
}

int main()
{
    const std::string input = "A_B A_B_C A_B_C_D A_B_C_D_E";
    bool ok = doParse(input, qi::blank);

    return ok? 0 : 255;
}
于 2012-09-06T12:40:53.633 回答