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

How to parse number after finding some word

我想解析下面提到的 JSON 并从中提取生产年份值

    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: '
    }'