2017-11-25 241 views
-2

我是相當新的Boost庫,我試圖用boost::split分裂以下字符串:分割使用boost ::字符串分割

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

我試圖分裂上面的字符串爲:

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

我不能使用逗號,作爲分隔符的分隔符,因爲引號內的項可能包含逗號。有沒有辦法可以指定忽略使用任何正則表達式引號內的分隔符?

+0

https://stackoverflow.com/questions/890895/using-escaped-list-separator-with-boost-split – negacao

+0

可能重複的可能的複製[使用轉義分割的\ _list \ _separator](https://stackoverflow.com/questions/890895/using-escaped-list-separator-with-boost-split) – mkaes

+0

爲了教育目的,一個簡單的正則表達式來分割它們: [a-zA-Z0-9。「](?:[a-zA-Z0-9。」\ s] *),| \ w \ d + – jsn

回答

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