解析为带有 qi 和替代部分的结构
Parsing into structs with qi and alternative parts
我使用精神解析器已经很长时间了,但现在我有一个我不太明白的问题。 我想将a,b->c,d或a,b->d之类的东西解析为结构。如果输入为 a,b->c,d(规则的左侧部分(,则以下代码将执行此操作。但是,如果输入是a,b->d(交替部分(,则产生aa,bb,,d。因此,替代解析器似乎不会清除已解析的部分。
struct Test
{
std::string a;
std::string b;
std::string c;
std::string d;
};
BOOST_FUSION_ADAPT_STRUCT(Test,
(std::string, a)
(std::string, b)
(std::string, c)
(std::string, d))
using namespace boost::spirit::qi;
using std::string;
using std::pair;
rule<const char *, Test()> r = (+alnum >> ',' >> +alnum >> "->" >> +alnum >> ',' >> +alnum) | (+alnum >> ',' >> +alnum >> "->" >> attr(string()) >> +alnum);
Test result;
//const char* s = "a,b->c,d"; //produces a Result with a,b,c,d
const char* s = "a,b->d"; // procudes a Result with aa,bb,,d
parse(s, s + strlen(s), r, result);
将其制作成一个独立的复制品:
活在魔杖盒上
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/adapted.hpp>
#include <iomanip>
#include <iostream>
namespace qi = boost::spirit::qi;
struct Test { std::string a, b, c, d; };
BOOST_FUSION_ADAPT_STRUCT(Test, a,b,c,d)
int main() {
qi::rule<const char *, Test()> static const r
= (+qi::alnum >> ',' >> +qi::alnum >> "->" >> +qi::alnum >> ',' >> +qi::alnum)
| (+qi::alnum >> ',' >> +qi::alnum >> "->" >> qi::attr(std::string()) >> +qi::alnum);
for (auto input : {
"a,b->c,d",
"a,b->d"
}) {
Test result;
qi::parse(input, input + strlen(input), r, result);
for (auto const& part: { result.a, result.b, result.c, result.d })
std::cout << " " << std::quoted(part);
std::cout << "n";
}
}
印刷
"a" "b" "c" "d"
"aa" "bb" "" "d"
因此,您的问题类似于:
- 了解 Boost.spirit 的字符串解析器
- 在灵气中使用可选的解析器
- 回滚气灵中替代解析器的变化
常见的解决方案是qi::hold[]
它有一些开销,但通常有效:
qi::rule<const char *, Test()> static const r
= qi::hold [+qi::alnum >> ',' >> +qi::alnum >> "->" >> +qi::alnum >> ',' >> +qi::alnum]
| (+qi::alnum >> ',' >> +qi::alnum >> "->" >> qi::attr(std::string()) >> +qi::alnum);
哪些打印在魔杖盒上直播
"a" "b" "c" "d"
"a" "b" "" "d"
相关文章:
- C++结构编译器错误询问向量的迭代器
- 如何使用迭代器指向结构体c++的向量
- 在VS 2017中,朋友通过具有私有析构函数的结构的unique_ptr向量进行迭代失败
- 迭代结构中包含的向量
- 为结构的向量创建C 矢量迭代器
- 是否有一个很好的方法可以在C 11中打印出像JSON一样的Trie结构(仅迭代解决方案)的扁平命名空间
- 有没有办法迭代不完整的结构
- 用于隐藏结构细节的迭代器适配器
- 在 stl 中迭代结构类型的队列
- 无法迭代结构"string"的哈希映射:[列表] C++
- Boost Intervocess:通过迭代通过从结构引用对象的映射进行迭代时
- 如何从数据结构的向量中收集迭代器
- 当迭代器添加到添加到列表向量的结构时,迭代器停止指向值?
- 使用POCO迭代JSON结构
- 是否值得两次通过文件进行迭代,以创建最小的数据结构
- 创建自定义迭代器结构以与CSTDIO一起使用
- 在编译时使用模板在跨结构字段中迭代
- 正在取消引用自定义结构字段的迭代器
- 使用C预处理器在结构字段上进行迭代
- 如何在boost::property_tree中迭代XML结构