首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >助推:精神部分跳跃

助推:精神部分跳跃
EN

Stack Overflow用户
提问于 2013-12-29 18:01:44
回答 1查看 149关注 0票数 3

请考虑以下解析器:

代码语言:javascript
复制
#include <assert.h>
#include <iostream>
#include <boost/spirit/include/qi.hpp>

namespace qi = boost::spirit::qi;

struct command_toten_parser : qi::grammar<const char *, std::string()> {
    command_toten_parser() : command_toten_parser::base_type(r) {
        r = *qi::blank >> *qi::graph >> *qi::blank;
    }
    qi::rule<const char *, std::string()> r;
};

int main(int argc, char *argv[]) {
    command_toten_parser p;
    std::string c, s(" asdf a1 a2 ");
    const char *b = &*s.begin();
    const char *e = &*s.end();

    assert(qi::parse(b, e, p, c));
    std::string rest(b, e);

    assert(c == std::string("asdf"));
    assert(rest == std::string("a1 a2 "));

    return 0;
}

如何更改解析器,使*qi::blank匹配的部分不被捕获(并且我的断言通过)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-29 19:35:05

您通常会使用一个船长:

代码语言:javascript
复制
qi::phrase_parse(b, e, +qi::graph, qi::blank, c);

会解析成c == "asdfa1a2"。显然,您希望不允许跳过“内部”令牌,让我们调用qi::lexeme

代码语言:javascript
复制
qi::phrase_parse(b, e, qi::lexeme [+qi::graph], qi::blank, c);

它解析"asdf",使"a1 a2 "不被解析。

完全调整的示例展示了如何使用语法结构来使用可配置的跳过器:

代码语言:javascript
复制
#include <assert.h>
#include <iostream>
#include <boost/spirit/include/qi.hpp>

namespace qi = boost::spirit::qi;

template <typename Skipper = qi::blank_type>
struct command_toten_parser : qi::grammar<const char *, std::string(), Skipper> {
    command_toten_parser() : command_toten_parser::base_type(r) {
        r = qi::lexeme [ +qi::graph ];
    }
    qi::rule<const char *, std::string(), Skipper> r;
};

int main(int argc, char *argv[]) {
    command_toten_parser<> p;
    std::string c, s(" asdf a1 a2 ");
    const char *b = &s[0];
    const char *e = b + s.size();

    assert(qi::phrase_parse(b, e, p, qi::blank, c));
    std::string rest(b, e);

    assert(c == std::string("asdf"));
    assert(rest == std::string("a1 a2 "));

    return 0;
}

看吧,住在Coliru

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20828371

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档