使用boost :: split拆分字符串

时间:2017-11-25 11:02:08

标签: c++ boost

我是一个相当新兴的库,我试图使用boost::split拆分以下字符串:

std::string line1 = R"(1500,"Rev, H., Tintin, K.H. Ken",204400,350)";

我正在尝试将上面的字符串拆分为:

{ "1500", "Rev, H., Tintin, K.H. Ken", "204400", "350"}

我不能使用逗号,作为拆分的分隔符,因为引号内的项可能包含逗号。有没有办法可以指定使用任何regexp忽略引号内的分隔符?

2 个答案:

答案 0 :(得分:0)

仅使用标准库:

<强> Live On Coliru

#include <iostream>
#include <sstream>
#include <iomanip>

int main() {
    std::istringstream line1(R"(1500,"Rev, H., Tintin, K.H. Ken",204400,350)");

    char ch;
    struct { int id;
        std::string full_title;
        int64_t some;
        int64_t data;
    } record;

    if ( (line1 >> record.id) 
      && (line1 >> ch && ch == ',')
      && (line1 >> std::quoted(record.full_title))
      && (line1 >> ch && ch == ',')
      && (line1 >> record.some)
      && (line1 >> ch && ch == ',')
      && (line1 >> record.data))
    {
        std::cout << "Parsed: \n";
        std::cout << "  record.id = " << record.id << "\n";
        std::cout << "  record.full_title = " << record.full_title << "\n";
        std::cout << "  record.some = " << record.some << "\n";
        std::cout << "  record.data = " << record.data << "\n";
    }
}

打印

Parsed: 
  record.id = 1500
  record.full_title = Rev, H., Tintin, K.H. Ken
  record.some = 204400
  record.data = 350

答案 1 :(得分:0)

使用提升精神:

<强> Live On Coliru

#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/adapt_struct.hpp>

struct Record {
    int id;
    std::string full_title;
    int64_t some;
    int64_t data;
};

BOOST_FUSION_ADAPT_STRUCT(Record, id, full_title, some, data)

namespace qi = boost::spirit::qi;

int main() {
    using It = std::string::const_iterator;
    qi::rule<It, std::string()> quoted = '"' >> *('\\' >> qi::char_ | ~qi::char_('"')) >> '"';
    qi::rule<It, Record()> parser = qi::skip(',') [qi::int_ >> quoted >> qi::int_ >> qi::int_];

    std::string const line1(R"(1500,"Rev, H., Tintin, K.H. Ken",204400,350)");

    Record record;
    if (parse(line1.begin(), line1.end(), parser, record))
    {
        std::cout << "Parsed: \n";
        std::cout << "  record.id = " << record.id << "\n";
        std::cout << "  record.full_title = " << record.full_title << "\n";
        std::cout << "  record.some = " << record.some << "\n";
        std::cout << "  record.data = " << record.data << "\n";
    }
}

打印

Parsed: 
  record.id = 1500
  record.full_title = Rev, H., Tintin, K.H. Ken
  record.some = 204400
  record.data = 350