Pages

boost::regex_search

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.

Using regex_search we could check if a string cointains a regular expression.

The function requires in input the string to be searched, a match, and the regular expression.

A match is an object of this class:

template <class Iterator,
class Allocator=std::allocator<sub_match<Iterator> >
class match_results;

A few handy typedefs are available to simplify its usage. In the example we are about to use smatch, a match for a (simple) string.

Here is the example:

#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 r02()
{
regex reg("(new)|(delete)");
smatch m;
string s = "Calls to new must be followed by delete.";

if(regex_search(s, m, reg))
{
if(m[1].matched)
cout << "(new), first expression in the regex, has been found" << endl;
}
}

No comments:

Post a Comment