Boost Spirit X3:跳过什么都不做的解析器

Boost Spirit X3: skip parser that would do nothing

我正在熟悉 boost spirit v3。我想问的问题是如何说明您不想以任何方式使用跳过解析器的事实。

考虑一个解析以逗号分隔的整数序列的简单示例:

#include <iostream>
#include <string>
#include <vector>

#include <boost/spirit/home/x3.hpp>

int main()
{
    using namespace boost::spirit::x3;

    const std::string input{"2,4,5"};

    const auto parser = int_ % ',';
    std::vector<int> numbers;

    auto start = input.cbegin();
    auto r = phrase_parse(start, input.end(), parser, space, numbers);

    if(r && start == input.cend())
    {
        // success
        for(const auto &item: numbers)
            std::cout << item << std::endl;
        return 0;
    }

    std::cerr << "Input was not parsed successfully" << std::endl;
    return 1;
}

这完全没问题。但是,我想禁止在两者之间有空格(即 "2, 4,5" 不应该被很好地解析)。

我尝试在 phrase_parse 中使用 eps 作为跳过解析器,但您可以猜到,程序最终陷入无限循环,因为 eps 匹配到一个空字符串。

我找到的解决方案是使用 no_skip 指令 (https://www.boost.org/doc/libs/1_75_0/libs/spirit/doc/html/spirit/qi/reference/directive/no_skip.html)。所以解析器现在变成:

const auto parser = no_skip[int_ % ','];

这工作正常,但我不认为它是一个优雅的解决方案(特别是在 phrase_parse 中提供 "space" 解析器,当我不想跳过空格时)。是否没有什么都不做的跳过解析器?我错过了什么吗?

感谢您的宝贵时间。期待任何回复。

您可以使用 no_skip[]lexeme[]。它们几乎相同,除了预跳过 (Boost Spirit lexeme vs no_skip)。

Are there no skip parsers that would simply do nothing? Am I missing something?

一个疯狂的猜测,但你可能错过了 parse API 首先不接受船长

Live On Coliru

#include <iostream>
#include <iomanip>
#include <boost/spirit/home/x3.hpp>
namespace x3 = boost::spirit::x3;

int main() {
    std::string const input{ "2,4,5" };
    auto f = begin(input), l = end(input);

    const auto parser = x3::int_ % ',';
    std::vector<int> numbers;

    auto r = parse(f, l, parser, numbers);

    if (r) {
        // success
        for (const auto& item : numbers)
            std::cout << item << std::endl;
    } else {
        std::cerr << "Input was not parsed successfully" << std::endl;
        return 1;
    }

    if (f!=l) {
        std::cout << "Remaining input " << std::quoted(std::string(f,l)) << "\n";
        return 2;
    }
}

版画

2
4
5