c++ - 阻止 X3 符号匹配子字符串

标签 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";
      }
    }
}

最佳答案

Qi 的存储库中曾经有distinct

X3 没有。

解决您所展示的情况的方法是一个简单的前瞻断言:

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

您也可以轻松创建一个独特帮助器,例如:

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

现在您可以解析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";
        }
    }
}

打印

Parsing 'foo': 1 Remaining: ''

Parsing 'foobar': Parse failed
Parsing 'barfoo': Parse failed

关于c++ - 阻止 X3 符号匹配子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33725521/

相关文章:

c++ - 类型名称不允许/意外

c++ - 直接对象初始化与使用转换函数初始化

c++ - C++11 是否优化了 lambda 中的尾递归调用?

c++ - 为什么删除元素的 std::for_each 不会中断迭代?

C++ boost::spirit::qi 递归规则

c++ - spirit x3 : locally defined rule definition must have an attribute attached?

c++ - 适用于 Windows Media Foundation 的 Visual Studio

c++ - 在 OpenGL 中绑定(bind)超过 MAX_TEXTURE_UNITS 个纹理

c++ - 来自备选方案的部分匹配的综合属性

c++ - 延迟初始化引用 - 用什么初始化?