【问题标题】:Parsing a list of strings followed by a list of strings with spirit x3解析一个字符串列表,后跟一个带有精神 x3 的字符串列表
【发布时间】:2016-11-26 12:32:37
【问题描述】:

我正在尝试使用 boost spirit x3 将字符串解析为结构:

struct identifier {
    std::vector<std::string> namespaces;
    std::vector<std::string> classes;
    std::string identifier;

};

现在我有一个解析器规则来匹配这样的字符串:

foo::bar::baz.bla.blub
foo.bar
boo::bar
foo

我的解析器规则如下所示。

auto const nested_identifier_def =
        x3::lexeme[
                -(id_string % "::")
                >> -(id_string % ".")
                >> id_string
        ];

其中id_string 解析alphanum 的组合。 我知道这条规则无法按照我的意愿进行解析,因为在解析 foo.bar 时,例如规则 -(id_string % ".") 的这一部分会消耗整个字符串。 如何更改规则以在结构中正确解析?

【问题讨论】:

    标签: c++ parsing c++14 boost-spirit boost-spirit-x3


    【解决方案1】:

    假设您的id_string 是这样的:

    auto const id_string = x3::rule<struct id_string_tag, std::string>{} =
        x3::lexeme[
                (x3::alpha | '_')
            >> *(x3::alnum | '_')
        ];
    

    那么我认为这就是你所追求的:

    auto const nested_identifier_def =
           *(id_string >> "::")
        >> *(id_string >> '.')
        >>  id_string;
    

    Online Demo

    问题在于p % delimitp &gt;&gt; *(delimit &gt;&gt; p) 的简写,即它总是在分隔符之后使用一个p 。但是你想要的是*(p &gt;&gt; delimit),这样在分隔符之后就不会消耗p,而是留给下一个规则。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-18
      • 1970-01-01
      • 2020-09-04
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      • 2013-08-11
      相关资源
      最近更新 更多