Pages

boost::regex_search /2

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.

In this example we use another overload of regex_search to scan a string to find how many elements of the passed regular expression are in it:

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

using std::cout;
using std::endl;
using std::string;
using boost::regex;
using boost::smatch;
using boost::regex_search;

void r03()
{
regex reg("(new)|(delete)");
smatch m;
string s = "Calls to new must be followed by delete. "
"Forgetting to call delete after a new results in a leak.";

cout << "Checking: " << s << endl;

int newNr = 0;
int delNr = 0;
string::const_iterator it = s.begin();
string::const_iterator end = s.end();

while(regex_search(it, end, m, reg))
{
if(m[1].matched)
{
cout << m[1] << " found, ";
++newNr;
}
if(m[2].matched)
{
cout << m[2] << " found, ";
++delNr;
}

// go on searching in the string
it = m[0].second;
}
cout << endl;

if(newNr == delNr)
cout << "Same number of new/delete in the string" << endl;
}

No comments:

Post a Comment