regex token iterator Example
suggest changeA std::regex_token_iterator provides a tremendous tool for extracting elements of a Comma Separated Value file. Aside from the advantages of iteration, this iterator is also able to capture escaped commas where other methods struggle:
const auto input = "please split,this,csv, ,line,\\,\n"s;
const regex re{ "((?:[^\\\\,]|\\\\.)+)(?:,|$)" };
const vector<string> m_vecFields{ sregex_token_iterator(cbegin(input), cend(input), re, 1), sregex_token_iterator() };
cout << input << endl;
copy(cbegin(m_vecFields), cend(m_vecFields), ostream_iterator<string>(cout, "\n"));
A notable gotcha with regex iterators is that the iterator stores a pointer to its regex. A temporary is destroyed at the end of the full expression, so the iterator then dangles, which is undefined behavior. An rvalue does not stay alive.
This snippet uses std names unqualified. The s suffix needs using namespace std::string_literals (C++14).
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents