boost::regex_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.

Instead of looping on regex_search to search all the occurrence of a regex in a string, we could use regex_iterator (or sregex_iterator for std::string) coupled with a for_each() call to scan the string.

Here is an example that scan in string all the comma separated numbers and then add them using a functor:

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

using std::cout;
using std::endl;
using std::string;
using std::for_each;
using boost::regex;
using boost::sregex_iterator;
using boost::regex_search;

namespace
{
class Adder
{
int sum_;
public:
Adder() : sum_(0) {}

template <typename T> void operator()(const T& what)
{
sum_ += atoi(what[1].str().c_str());
}

int sum() const
{
return sum_;
}
};
}

void r06() {
regex reg("(\\d+),?");
string s = "1,1,2,3,5,8,13,21,34,55";

sregex_iterator it(s.begin(), s.end(), reg);
sregex_iterator end;

int sum = for_each(it, end, Adder()).sum();
cout << "summing " << s << ": " << sum << endl;
}

No comments:

Post a Comment