c++ - Boost spirit : how to parse string of value pairs into map<string, string> 然后返回?

标签 c++ parsing boost boost-spirit

所以有一个像 remixsettings_bits=1 这样的字符串;所见即所得=1,2,3,abc; remixclosed_tabs=0; remixgroup_closed_tabs=786432;混合语言=0;混音 = 5; remixsid=35d4f9907281708019490d07728c27ca5c10e5de7a869c322222225e3219e; audio_vol=100 我想知道如何使用 boost::spirit 将它们解析为 map name <-> value 并且能够使用 boost::spirit 将其写回?

更新: 所以我做了什么:

#include <iostream>
#include <sstream>
#include <string>
#include <map>
//...

std::map<std::string, std::string> user_control::parse_cookie( std::string cookie_data )
{
    std::map<std::string, std::string> parsed_cookie;
    std::string token, token2;
    std::istringstream iss(cookie_data);
    while ( getline(iss, token, ' ') )
    {
        std::string name, val;
        std::istringstream iss2(token);
        int num = 0 ;
        while ( getline(iss2, token2, '=') )
        {
            if ( num == 0)
            {
                name = token2;
                num++;
            }
            else
            {
                val = token2;
                std::string::iterator it = val.end() - 1;
                if (*it == ';')
                    val.erase(it);

            }
        }
        std::cout << "name: " << name <<  " value: " << val << std::endl;
        parsed_cookie.insert(std::pair<std::string, std::string>(name, val));
    }
    return parsed_cookie;
}

但我真的很想知道如何将我的代码移植到 boost::spirit 代码中。

最佳答案

这应该可以解决问题,解析对并使用 Karma 打印结果,尽管我们可能都应该去阅读 Hartmut 的文章!

#include <boost/spirit/include/qi.hpp>         // Parsing
#include <boost/spirit/include/karma.hpp>      // Generation
#include <boost/fusion/adapted/std_pair.hpp>   // Make std::pair a fusion vector

int main( int argc, char**argv)
{
  using namespace boost::spirit;
  std::string str = "keyA=value1; keyB=value2;keyC=value3;";

  std::map<std::string,std::string> contents;
  std::string::iterator first = str.begin();
  std::string::iterator last  = str.end();

  const bool result = qi::phrase_parse(first,last, 
   *( *(qi::char_-"=")  >> qi::lit("=") >> *(qi::char_-";") >> -qi::lit(";") ),
    ascii::space, contents);                                  

  assert(result && first==last);

  std::cout << karma::format(*(karma::string << '=' <<
               karma::string << karma::eol), contents);
}

关于c++ - Boost spirit : how to parse string of value pairs into map<string, string> 然后返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6789517/

相关文章:

android - 使用任意 Boost 库进行奇怪的 NDK 编译

c++ - 多线程实时音频编程 - 阻塞或不阻塞

php - 解析 Twitter API 日期戳

c++ - 我可以使用 std::shared_ptr 而不是 boost::shared_ptr 构建 boost 库吗

sockets - 无法使用 boost asio 设置 TCP 源端口

python - 从类似 JSON 的 blob 中解析出这个值的最 Pythonic 方法是什么?

c++ - 我还应该在 C++11 中返回 const 对象吗?

c++ - QT - 如何将文件名编码设置为西里尔文

c++通过串联迭代push_back?

r - 如何在 R 中提取函数(写为字符串)中的参数?