c++ - 如何使用 boost.Spirit 解析带有嵌套括号的表达式?

标签 c++ grammar boost-spirit boost-spirit-qi

我需要解析包含键/值对和键/子表达式对的 1 行表达式,例如:

123=a 456=b 789=(a b c) 111=((1=a 2=b 3=c) (1=x 2=y 3=z) (123=(x y z))) 666=evil

为了使解析器更简单,我愿意分几步进行解析,将第一级标签(这里是123、456、789、111和666)分开,然后在另一步中解析它们的内容。 这里 789 的值是 "a b c",111 的值是 (1=a 2=b 3=c) (1=x 2=y 3=z) (123=(x y z) ))

但是语法在这一点上打败了我,所以我可以找到一种方法来获取匹配括号之间的表达式。我得到的 111 是 (1=a 2=b 3=c,以第一个右括号结束。

我找到了这个方便的示例并尝试使用它,但没有成功:

#include <map>
#include <string>
#include <boost/spirit/include/classic.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/std_pair.hpp>

namespace qi = boost::spirit::qi;

void main()
{
    auto                                                                   value = +qi::char_("a-zA-Z_0-9");
    auto                                                                   key   =  qi::char_("a-zA-Z_") >> *qi::char_("a-zA-Z_0-9");
    qi::rule<std::string::iterator, std::pair<std::string, std::string>()> pair  =  key >> -('=' >> value);
    qi::rule<std::string::iterator, std::map<std::string, std::string>()>  query =  pair >> *((qi::lit(';') | '&') >> pair);

    std::string input("key1=value1;key2;key3=value3");  // input to parse
    std::string::iterator begin = input.begin();
    std::string::iterator end = input.end();

    std::map<std::string, std::string> m;        // map to receive results
    bool result = qi::parse(begin, end, query, m);   // returns true if successful
}

我怎样才能做到这一点?

编辑:我在 http://boost-spirit.com/home/articles/qi-example/parsing-a-list-of-key-value-pairs-using-spirit-qi/ 找到了示例

最佳答案

你可以将其写为:

qi::rule<std::string::iterator, std::pair<std::string, std::string>()> pair = 
        key >> -(
           '=' >> ( '(' >> raw[query] >> ')' | value )
        )
    ;

它将所有嵌入的查询存储为与键关联的值(字符串)。不过,这将从存储的值中删除括号。如果您仍然希望将括号存储在返回的属性中,请使用:

qi::rule<std::string::iterator, std::pair<std::string, std::string>()> pair = 
        key >> -(
           '=' >> ( raw['(' >> query >> ')'] | value )
        )
    ;

关于c++ - 如何使用 boost.Spirit 解析带有嵌套括号的表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5662206/

相关文章:

c++ - boost::spirit::qi 规则减少解析错误

c++ - 动态地形 block 生成

C# 语法 "base"

c++ - chrono_literals 不是命名空间名称

python - BASIC语法中 "END"和 "END IF"之间的冲突,使用Lark

java - 在 Javadocs 中,我应该如何在 <code> 标签中编写复数形式的单数对象?

boost - 如何向基于 boost::spirit::lex 的词法分析器添加符号表接口(interface)?

c++ - 字符串到 bool 表达式不起作用 C++

c++ - 以 vector 为成员变量的对象复制构造函数

c++ - C++ 的 XCode 错误 "Undefined symbols for architecture x86_64"