我正在学习如何使用boost::spirit,即使使用非常简单的解析器,我也面临一些问题。我正在尝试构建一个解析器,它接受由冒号分隔的数字列表(只有 0 或 1)。该列表可以有 3 位或 4 位数字。因此,0:0:0
并且1:0:1:0
是有效的,而例如0:0
或0:0:0:0:0
不是。
在下面的代码中,您可以看到我如何使用可选运算符来指定第一个数字可能存在或不存在。但是,它不起作用(对 sequence 的解析失败0:0:0
)。代码有什么问题吗?我会说这是正确的,但我还是刚刚开始学习 Spirit。
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;
namespace phoenix = boost::phoenix;
void parse_tuple(const std::string& tuple) {
using qi::char_;
auto begin = tuple.begin();
auto end = tuple.end();
bool r = qi::parse(begin, end,
-(char_('0', '1') >> ':') >>
char_('0', '1') >> ':' >>
char_('0', '1') >> ':' >>
char_('0', '1')
);
if (!r || begin != end)
throw std::runtime_error("wrong format");
}
int main() {
parse_tuple("0:0:0"); // It fails for this one
parse_tuple("0:0:0:0");
try { parse_tuple("0:0"); } catch (...) {
std::cout << "expected error\n"; }
try { parse_tuple("0:0:0:0:0"); } catch (...) {
std::cout << "expected error\n"; }
}