Gab*_*iel 2 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
Run Code Online (Sandbox Code Playgroud)
为了使解析器更简单,我愿意在几个步骤中进行解析,分离第一级标记(这里是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
}
Run Code Online (Sandbox Code Playgroud)
我怎么能这样做?
编辑:我在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 )
)
;
Run Code Online (Sandbox Code Playgroud)
它将所有嵌入的查询存储为与密钥关联的值(字符串).但是,这将从存储的值中删除括号.如果您仍希望将括号存储在返回的属性中,请使用以下命令:
qi::rule<std::string::iterator, std::pair<std::string, std::string>()> pair =
key >> -(
'=' >> ( raw['(' >> query >> ')'] | value )
)
;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2125 次 |
| 最近记录: |