gpt4 book ai didi

c++ - Boost::spirit 部分跳过

转载 作者:太空狗 更新时间:2023-10-29 21:44:11 24 4
gpt4 key购买 nike

考虑以下解析器:

#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 匹配的部分(并且我的断言通过)

最佳答案

您通常会使用船长:

qi::phrase_parse(b, e, +qi::graph, qi::blank, c);

将解析为 c == "asdfa1a2"。显然,您想禁止跳过 token “内部”,让我们调用 qi::lexeme:

qi::phrase_parse(b, e, qi::lexeme [+qi::graph], qi::blank, c);

它解析 "asdf" 并留下 "a1 a2 " 未解析。

完全调整的示例显示了如何将可配置的 skipper 与语法结构一起使用:

#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;
}

查看 Live On Coliru

关于c++ - Boost::spirit 部分跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20828371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com