正如他们在评论中建议的那样,最简单的方法是使用解析器库。
C++ 中最好的解析器库之一是Boost.Spirit。
这是一个如何使用 Boost.Spirit 解析格式的工作示例:
#include <iostream>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_parse.hpp>
#include <boost/variant.hpp>
#include <boost/variant/get.hpp>
using Element = boost::variant<
std::string,
std::vector<std::string>
>;
std::ostream& operator<<(std::ostream& s, Element const& e) {
switch(e.which()) {
case 0:
return s << boost::get<std::string>(e);
case 1:
for(auto const& a : boost::get<std::vector<std::string>>(e))
s << a << ' ';
return s;
}
throw;
}
std::vector<Element> parse(std::string const& input) {
namespace qi = boost::spirit::qi;
using namespace std;
using I = decltype(input.begin());
using S = qi::space_type;
struct string2 : string {
using string::string;
string2(char c) : string(1, c) {} // Need this extra constructor for +qi::alnum.
};
// Grammar.
qi::rule<I, S, string2> element = +qi::alnum;
qi::rule<I, S> open = qi::lit('"');
qi::rule<I, S> close = qi::lit('"');
qi::rule<I, S, vector<string>> nested_element = open >> (element % ',') >> close;
qi::rule<I, S, Element> element2 = element | nested_element;
qi::rule<I, S, vector<Element>> parser = element2 % ',';
vector<Element> result;
auto cur = input.begin();
if(!phrase_parse(cur, input.end(), parser, qi::space, result) || cur != input.end())
throw "Failed to parse.";
return result;
}
int main() {
auto elements = parse("a, b, \"c, d, e\", f");
for(auto const& e : elements)
std::cout << e << '\n';
}
输出:
a
b
c d e
f