gpt4 book ai didi

c++ - 找到某个单词后如何解析数字

转载 作者:搜寻专家 更新时间:2023-10-31 02:11:32 24 4
gpt4 key购买 nike

我想解析下面提到的 JSON 并从中提取 productionYear 值

    auto data = {
"cars" : [
{
"name" : "BMW",
"engine" : 3.0
},
{
"name" : "Citroen",
"engine" : 3.6
},
{
"name" : "Ferrari",
"engine" : 4.2
}
],
"productionYear" : 1999
}

我有以下规则:

    using boost::spirit::ascii::string;
using boost::spirit::omit;
using boost::spirit::qi::lit;
using boost::spirit::qi::char_;

boost::spirit::qi::rule<std::string::iterator, int()> production_;
production_ = omit[*(char_ - "productionYear") >>
lit('"') >> lit(' ') >> lit(':') >> lit(' ')] >> int_;

int year;
auto it = data.begin();

if (boost::spirit::qi::parse(it, data.end(), production_, year))
{
std::cout << "Parse finished with succeded status"
<< std::distance(data.begin(), it);
}

解析器失败,最后一个迭代器位置:0

谁能告诉我我做错了什么?

最佳答案

DISCLAIMER

Do not do this. Use a JSON parser. There are plenty. Your grammar is brittle in a gazillion ways. (You will stop on productionYear inside another value, as partial match in a longer key, as a property of nested/sibling objects, UNICODE escapes, escapes. You will not allow valid JSON optional whitespace, etc.).

See here for what it takes to parse JSON in Spirit, to a reasonable extent: https://github.com/sehe/spirit-v2-json/blob/master/json.cpp

*(char_ - "productionYear") 

解析任何直到(但不包括)productionYear 的文本。

这意味着下一个字符永远不会匹配 '"'(因为它是 'p')。

一个直接的解决方法是

#include <boost/spirit/include/qi.hpp>

namespace qi = boost::spirit::qi;

int main() {
std::string const data = R"({
"cars": [{
"name": "BMW",
"engine": 3.0
},
{
"name": "Citroen",
"engine": 3.6
},
{
"name": "Ferrari",
"engine": 4.2
}],
"productionYear" : 1999
})";

boost::spirit::qi::rule<std::string::const_iterator, int()> production_;
production_ = qi::omit[+(qi::char_ - "productionYear") >> "productionYear\"" >> ' ' >> ':' >> ' '] >> qi::int_;

int year;
auto it = data.begin(), last = data.end();

if (qi::parse(it, last, production_, year)) {
std::cout << "Parsed: " << year << "\n";
} else {
std::cout << "Parsed failed\n";
}

if (it != last)
std::cout << "Remaining input: '" << std::string(it, last) << "'\n";
}

Live On Coliru

输出:

Parsed: 1999
Remaining input: '
}'

关于c++ - 找到某个单词后如何解析数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43392039/

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