停止匹配子字符串中的X3符号

时间:2015-11-15 21:49:48

标签: c++ c++11 boost-spirit boost-spirit-x3

如何阻止X3符号解析器匹配部分令牌?在下面的示例中,我想匹配" foo",但不是" foobar"。我尝试将符号解析器抛出到lexeme指令中,就像标识符一样,但是没有任何匹配。

感谢您的任何见解!

#include <string>
#include <iostream>
#include <iomanip>

#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"
        })
    {
      using namespace boost::spirit::x3;

      std::cout << "\nParsing " << std::left << std::setw(20) << ("'" + input + "':");

      int v;
      auto iter = input.begin();
      auto end  = input.end();
      bool ok;
      {
        // what's right rule??

        // this matches nothing
        // auto r = lexeme[sym - alnum];

        // this matchs prefix strings
        auto r = sym;

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

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

1 个答案:

答案 0 :(得分:3)

Qi以前在他们的存储库中有exported

X3没有。

在你展示的案例中解决它的问题是一个简单的先行断言:

distinct

您也可以轻松制作auto r = lexeme [ sym >> !alnum ]; 助手,例如:

distinct

现在你可以解析auto kw = [](auto p) { return lexeme [ p >> !(alnum | '_') ]; };

<强> Live On Coliru

kw(sym)

打印

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