boost::regex_token_iterator

As an introduction to some of the most interesting boost libraries you can read "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. That's what I'm actually doing, and these are a few notes that I'm jotting down in the meanwhile.

Here is an example for regex_token_iterator (sregex_token_iterator the typedef for its std::string version) that shows how to use it for splitting a string accordingly to a specific regex:

#include <iostream>
#include <vector>
#include <string>
#include "boost/regex.hpp"

using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::ostream_iterator;
using boost::regex;
using boost::sregex_token_iterator;

void r07() {
regex reg("/");
string s = "Split/Values/Separated/By/Slashes";
vector<string> vec;

sregex_token_iterator it(s.begin(), s.end(), reg, -1);
sregex_token_iterator end;
while(it != end)
vec.push_back(*it++);

cout << s << endl;
copy(vec.begin(), vec.end(), ostream_iterator<string>(cout, " "));
}

No comments:

Post a Comment