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