首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >精神::气保白

精神::气保白
EN

Stack Overflow用户
提问于 2020-05-01 19:11:10
回答 1查看 154关注 0票数 1

我使用这段代码将"k1=v1;k2=v2;k3=v3;kn=vn“字符串解析为一个映射。

代码语言:javascript
复制
    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

简单地说,我想要保留原来的字符串(键和值),然后用'=‘进行拆分。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-01 23:38:34

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

代码语言:javascript
复制
qi::parse(
  begin,end,
  *(*~qi::char_(";=") >> '=' >> *~qi::char_(';') >> -qi::lit(';')),
  dict);

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

代码语言:javascript
复制
qi::phrase_parse(
  begin, end,
  *(qi::lexeme[+(qi::graph - '=')]
     >> '='
     >> qi::lexeme[*~qi::char_(';')] >> (qi::eoi|';')),
  qi::ascii::space, dict);

链接答案确实给出了更多的技术/背景,说明如何在齐与跳船一起工作。

演示时间

住在Coliru

代码语言:javascript
复制
#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";
        }
    }

}

打印

代码语言:javascript
复制
-------------------------
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;"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61549182

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档