gpt4 book ai didi

c++ - 类似 Parse 的 CSV(空白分隔符和 boost )

转载 作者:行者123 更新时间:2023-11-30 05:42:12 25 4
gpt4 key购买 nike

我想解析一个类似 CSV 的文件,符合 boost.有许多不同的方法,例如 split、tokenise、spirit、regex...

解析行可能如下所示:"abc""def""hij\"hgfd\""结果应该是这样的:

"abc"
"def"
"hij \"hgfd\" "

我认为将 boost 的标记化与 escaped_list_separator 一起使用是个好主意,但不可能在空白分隔符上拆分,不是吗?

最佳答案

这是一个快速而肮脏的匹配你使用 Spirit 描述的内容(多行到一个 vector >):

Live On Coliru

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_match.hpp>
namespace qi = boost::spirit::qi;

int main() {
std::vector<std::vector<std::string>> csv_data;

if (std::cin
>> std::noskipws
>> qi::phrase_match(*qi::lexeme['"' >> *('\\' >> qi::char_ | ~qi::char_("\r\n\"")) >> '"'] % qi::eol, qi::blank, csv_data))
{
std::cout << "Parse succeeded: " << csv_data.size() << "\n";
for(auto& row: csv_data) {
for(auto& c: row) std::cout << c << '|';
std::cout << "\n";
}
} else {
std::cout << "Parse failed\n";
}
}

示例打印:

Parse succeeded: 3
abc|def|hij "hgfd" |
qwehjr|aweqwejkl||

For a background on parsing (optionally) quoted delimited fields, including different quoting characters (', "), see here:

For a very, very, very complete example complete with support for partially quoted values and a

splitInto(input, output, ' ');

method that takes 'arbitrary' output containers and delimiter expressions, see here:

关于c++ - 类似 Parse 的 CSV(空白分隔符和 boost ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30751584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com