2

我正在尝试使用 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 % ".")会消耗整个字符串。如何更改规则以在结构中正确解析?

4

1 回答 1

3

假设你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 % delimit是 的简写p >> *(delimit >> p),即它总是在分隔符p 之后消耗一个。但是,您想要的是*(p >> delimit)nop在分隔符之后被消耗,而是留给下一个规则。

于 2016-07-22T16:55:06.173 回答