我想要一个名称-值对的列表。每个列表以“。”结尾。和停产。每个名称/值对之间用“:”分隔。每对之间用“;”分隔在列表中。例如。

NAME1: VALUE1; NAME2: VALUE2; NAME3: VALUE3.<EOL>

我的问题是值包含“。”并且最后一个值始终使用“。”在EOL。我可以使用某种先行方式来确保最后一个'。'在对EOL进行不同对待之前?

最佳答案

我创建了一个样本,大概看起来像您所拥有的。该调整在以下行中:

value = lexeme [ *(char_ - ';' - ("." >> (eol|eoi))) ];

请注意- ("." >> (eol|eoi)))的含义:排除行尾或输入结束后紧跟的任何.

测试用例(也存在于http://liveworkspace.org/code/949b1d711772828606ddc507acf4fb4b上):
const std::string input =
    "name1: value 1; other name : value #2.\n"
    "name.sub1: value.with.periods; other.sub2: \"more fun!\"....\n";
bool ok = doParse(input, qi::blank);

输出:
parse success
data: name1 : value 1 ; other name  : value #2 .
data: name.sub1 : value.with.periods ; other.sub2 : "more fun!"... .

完整代码:
#include <boost/fusion/adapted.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>
#include <map>
#include <vector>

namespace qi    = boost::spirit::qi;
namespace karma = boost::spirit::karma;
namespace phx   = boost::phoenix;

typedef std::map<std::string, std::string> map_t;
typedef std::vector<map_t> maps_t;

template <typename It, typename Skipper = qi::space_type>
    struct parser : qi::grammar<It, maps_t(), Skipper>
{
    parser() : parser::base_type(start)
    {
        using namespace qi;

        name  = lexeme [ +~char_(':') ];
        value = lexeme [ *(char_ - ';' - ('.' >> (eol|eoi))) ];
        line  = ((name >> ':' >> value) % ';') >> '.';
        start = line % eol;
    }

  private:
    qi::rule<It, std::string(), Skipper> name, value;
    qi::rule<It, map_t(), Skipper> line;
    qi::rule<It, maps_t(), Skipper> start;
};

template <typename C, typename Skipper>
    bool doParse(const C& input, const Skipper& skipper)
{
    auto f(std::begin(input)), l(std::end(input));

    parser<decltype(f), Skipper> p;
    maps_t data;

    try
    {
        bool ok = qi::phrase_parse(f,l,p,skipper,data);
        if (ok)
        {
            std::cout << "parse success\n";
            for (auto& line : data)
                std::cout << "data: " << karma::format_delimited((karma::string << ':' << karma::string) % ';' << '.', ' ', line) << '\n';
        }
        else    std::cerr << "parse failed: '" << std::string(f,l) << "'\n";

        //if (f!=l) std::cerr << "trailing unparsed: '" << std::string(f,l) << "'\n";
        return ok;
    } catch(const qi::expectation_failure<decltype(f)>& e)
    {
        std::string frag(e.first, e.last);
        std::cerr << e.what() << "'" << frag << "'\n";
    }

    return false;
}

int main()
{
    const std::string input =
        "name1: value 1; other name : value #2.\n"
        "name.sub1: value.with.periods; other.sub2: \"more fun!\"....\n";
    bool ok = doParse(input, qi::blank);

    return ok? 0 : 255;
}

关于c++ - 提前解决歧义的boost::spirit::qi语法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12217515/

10-12 14:56