C++11 使得使用regex_token_iterator处理转义逗号变得非常容易:
std::stringstream ss(sText);
std::string item;
const regex re{"((?:[^\\\\,]|\\\\.)*?)(?:,|$)"};
std::getline(ss, item)
m_vecFields.insert(m_vecFields.end(), sregex_token_iterator(item.begin(), item.end(), re, 1), sregex_token_iterator());
顺便说一句,如果您只是想vector<string>从 CSV构造一个,string例如item您可以这样做:
const regex re{"((?:[^\\\\,]|\\\\.)*?)(?:,|$)"};
vector<string> m_vecFields{sregex_token_iterator(item.begin(), item.end(), re, 1), sregex_token_iterator()};
[现场示例]
一些快速的解释regex可能是有序的。(?:[^\\\\,]|\\\\.)匹配转义字符或非','字符。(有关更多信息,请参见此处:https ://stackoverflow.com/a/7902016/2642059 )这*?意味着它不是贪婪匹配,因此它将在第一次 ','到达时停止。所有嵌套在一个捕获中,由最后一个参数 the 1, to 选择regex_token_iterator。最后,(?:,|$)将匹配','-delimiter 或string.
为了使这个标准的 CSV 阅读器忽略空元素,可以更改正则表达式以仅匹配具有多个字符的字符串。
const regex re{"((?:[^\\\\,]|\\\\.)+?)(?:,|$)"};
请注意,'+'现在已经替换了'*'指示的 1 个或多个匹配字符。这将阻止它匹配以 .item结尾的字符串','。你可以在这里看到一个例子:http: //ideone.com/W4n44W