使用带有boost拆分的escaped_list_separator

Jam*_*ook 4 c++ boost split tokenize

我正在使用boost字符串库,并且刚刚遇到了分割方法的简单易用性.

  string delimiters = ",";
  string str = "string, with, comma, delimited, tokens, \"and delimiters, inside a quote\"";
  // If we didn't care about delimiter characters within a quoted section we could us
  vector<string> tokens;  
  boost::split(tokens, str, boost::is_any_of(delimiters));
  // gives the wrong result: tokens = {"string", " with", " comma", " delimited", " tokens", "\"and delimiters", " inside a quote\""}
Run Code Online (Sandbox Code Playgroud)

这将是美好而简洁的...但它似乎不适用于引号,而是我必须做类似以下的事情

string delimiters = ",";
string str = "string, with, comma, delimited, tokens, \"and delimiters, inside a quote\"";
vector<string> tokens; 
escaped_list_separator<char> separator("\\",delimiters, "\"");
typedef tokenizer<escaped_list_separator<char> > Tokeniser;
Tokeniser t(str, separator);
for (Tokeniser::iterator it = t.begin(); it != t.end(); ++it)
    tokens.push_back(*it);
// gives the correct result: tokens = {"string", " with", " comma", " delimited", " tokens", "\"and delimiters, inside a quote\""}
Run Code Online (Sandbox Code Playgroud)

我的问题是可以拆分或使用引用分隔符时使用其他标准算法?感谢purpledog,但我已经有了一种不贬低的方法来实现预期的结果,我只是认为它非常麻烦,除非我能用更简单,更优雅的解决方案替换它,我不会在没有首先将其包装的情况下使用它另一种方法.

编辑:更新代码以显示结果并澄清问题.

Jam*_*ook 5

使用boost :: split方法似乎没有任何简单的方法可以做到这一点.我能找到的最短的代码就是

vector<string> tokens; 
tokenizer<escaped_list_separator<char> > t(str, escaped_list_separator<char>("\\", ",", "\""));
BOOST_FOREACH(string s, escTokeniser)
    tokens.push_back(s);  
Run Code Online (Sandbox Code Playgroud)

这比原始片段略微冗长

vector<string> tokens;  
boost::split(tokens, str, boost::is_any_of(","));
Run Code Online (Sandbox Code Playgroud)