使用boost :: split分开字符串

Splitting a string using boost::split

本文关键字:字符串 split boost 使用      更新时间:2023-10-16

我对提升库是相当新的,我正在尝试使用 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?

忽略定界符

仅使用标准库:

活在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

使用boost精神:

活在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