首页 > 解决方案 > boost::spirit::qi 保留空白

问题描述

我正在使用此代码将“k1=v1;k2=v2;k3=v3;kn=vn”字符串解析为地图。

    qi::phrase_parse(
      begin,end,
      *(*~qi::char_('=') >> '=' >> *~qi::char_(';') >> -qi::lit(';')),
      qi::ascii::space, dict);

上面的代码将删除空格字符,例如“some_key=1 2 3”变为 some_key -> 123

我不知道如何删除或用第四个参数替换什么:qi::ascii::space

基本上,我想在用'='分割后保留原始字符串(键和值)。

我对精神没有太多的经验/知识。它确实需要投入时间来学习。

标签: c++boost-spirit-qi

解决方案


如果您不想要船长,只需使用qi::parse代替qi::phrase_parse

qi::parse(
  begin,end,
  *(*~qi::char_(";=") >> '=' >> *~qi::char_(';') >> -qi::lit(';')),
  dict);

但是,您可能确实希望有选择地跳过空格。最简单的方法通常是有一个通用的船长,然后标记词位区域(您不允许船长的地方):

qi::phrase_parse(
  begin, end,
  *(qi::lexeme[+(qi::graph - '=')]
     >> '='
     >> qi::lexeme[*~qi::char_(';')] >> (qi::eoi|';')),
  qi::ascii::space, dict);

链接的答案确实提供了更多关于如何在 Qi 中与船长合作的技术/背景

演示时间

住在科利鲁

#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/adapted/std_pair.hpp>
#include <map>
#include <iomanip>
namespace qi = boost::spirit::qi;

int main() {
    for (std::string const& input : { 
            R"()",
            R"(foo=bar)",
            R"(foo=bar;)",
            R"( foo = bar ; )",
            R"( foo = bar ;
foo 
= qux; baz =

    quux 
corge grault
 thud

; x=)",
            // failing:
            R"(;foo = bar;)",
        })
    {
        std::cout << "-------------------------\n";
        auto f=begin(input), l=end(input);

        std::multimap<std::string, std::string> dict;

        bool ok = qi::phrase_parse(f, l,
          (qi::lexeme[+(qi::graph - '=' - ';')]
             >> '='
             >> qi::lexeme[*~qi::char_(';')]
          ) % ';',
          qi::space,
          dict);

        if (ok) {
            std::cout << "Parsed " << dict.size() << " elements:\n";
            for (auto& [k,v]: dict) {
                std::cout << " - " << std::quoted(k) << " -> " << std::quoted(v) << "\n";
            }
        } else {
            std::cout << "Parse failed\n";
        }

        if (f!=l) {
            std::cout << "Remaining input: " << std::quoted(std::string(f,l)) << "\n";
        }
    }

}

印刷

-------------------------
Parse failed
-------------------------
Parsed 1 elements:
 - "foo" -> "bar"
-------------------------
Parsed 1 elements:
 - "foo" -> "bar"
Remaining input: ";"
-------------------------
Parsed 1 elements:
 - "foo" -> "bar "
Remaining input: "; "
-------------------------
Parsed 4 elements:
 - "baz" -> "quux 
corge grault
 thud

"
 - "foo" -> "bar "
 - "foo" -> "qux"
 - "x" -> ""
-------------------------
Parse failed
Remaining input: ";foo = bar;"

推荐阅读