所以有一个像 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/