regex token iterator Example

suggest change

A 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"));

Live Example

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).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents