请考虑以下解析器:
#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匹配的部分不被捕获(并且我的断言通过)
发布于 2013-12-29 19:35:05
您通常会使用一个船长:
qi::phrase_parse(b, e, +qi::graph, qi::blank, c);会解析成c == "asdfa1a2"。显然,您希望不允许跳过“内部”令牌,让我们调用qi::lexeme
qi::phrase_parse(b, e, qi::lexeme [+qi::graph], qi::blank, c);它解析"asdf",使"a1 a2 "不被解析。
完全调整的示例展示了如何使用语法结构来使用可配置的跳过器:
#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
https://stackoverflow.com/questions/20828371
复制相似问题