gpt4 book ai didi

c++ - 用qi和其他部分解析为结构

转载 作者:行者123 更新时间:2023-12-01 14:58:23 25 4
gpt4 key购买 nike

我使用精神分析器已经很长时间了,但是现在我有一个我不太了解的问题。
我想将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);

最佳答案

使其成为一个独立的副本:

Live On Wandbox

#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"

因此,您的问题类似于:
  • Understanding Boost.spirit's string parser
  • Use of optional parser in spirit qi
  • Rolling back changes in alternative parsers in qi 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);

    哪个打印 Live On Wandbox
     "a" "b" "c" "d"
    "a" "b" "" "d"

    关于c++ - 用qi和其他部分解析为结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59262349/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com