Stop X3 symbols from matching substrings

心已入冬 提交于 2019-11-29 16:16:25

Qi used to have distinct in their repository.

X3 doesn't.

The thing that solves it for the case you showed is a simple lookahead assertion:

auto r = lexeme [ sym >> !alnum ];

You could make a distinct helper easily too, e.g.:

auto kw = [](auto p) { return lexeme [ p >> !(alnum | '_') ]; };

Now you can just parse kw(sym).

Live On Coliru

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

int main() {

    boost::spirit::x3::symbols<int> sym;
    sym.add("foo", 1);

    for (std::string const input : { "foo", "foobar", "barfoo" }) {

        std::cout << "\nParsing '" << input << "': ";

        auto iter      = input.begin();
        auto const end = input.end();

        int v = -1;
        bool ok;
        {
            using namespace boost::spirit::x3;
            auto kw = [](auto p) { return lexeme [ p >> !(alnum | '_') ]; };

            ok = phrase_parse(iter, end, kw(sym), space, v);
        }

        if (ok) {
            std::cout << v << " Remaining: '" << std::string(iter, end) << "'\n";
        } else {
            std::cout << "Parse failed";
        }
    }
}

Prints

Parsing 'foo': 1 Remaining: ''

Parsing 'foobar': Parse failed
Parsing 'barfoo': Parse failed
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!