The regex_iterator Class Template

19.2. The regex_iterator Class Template

The class template regex_iterator is defined in the header <regex>.

namespace std {      // C++ standard library
 namespace tr1  {    // TR1 additions

    // CLASS TEMPLATE regex_iterator
template <class BidIt,
     class Elem = typename iterator_traits <BidIt>::value_type,
     class RXtraits = regex_traits <Elem> > class regex_iterator;

typedef regex_iterator <const char*>
typedef regex_iterator <const wchar_t*>
typedef regex_iterator <string::const_iterator>
typedef regex_iterator <wstring::const_iterator>

} }

This class template hides the details that we looked at in the first section. A search program similar to the last example but using regex_iterator looks like this.

Figure. Searching (regexiter/rgxiterator.cpp)

#include <regex>
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
using std::tr1::regex; using std::tr1::cregex_iterator;
using std::tr1::cmatch;
using std::cout; using std::string;
using std::ostream_iterator; using std::copy;

namespace std {      // add inserter to namespace std
template <class Elem, class  Alloc>
basic_ostream <Elem, Alloc>& operator <<(
  basic_ostream <Elem, Alloc>& out, const cmatch& val)
  {  // insert cmatch object into stream
  static string empty("[empty]");
  return out << (val.length() ? val.str() : empty);

int main()
  { // demonstrate use of cregex_iterator
  const char *expr = "a*|c";
  const char *tgt = "bcd";
  regex rgx(expr);
  const char *end = tgt + strlen(tgt);
  cregex_iterator first(tgt, end, rgx), last;
  ostream_iterator <cmatch> out(cout, "\n");
  copy(first, last, out);
  return 0;

The program creates a regular expression object, rgx, that holds the regular expression to search for. Then the program creates a regex_iterator object,[2] first, passing two iterators that delineate the target text and passing the regular expression object. The program also creates an end-of-sequence iterator, last. These two iterators describe a sequence of match_results objects, with successive elements in the sequence holding the results of successive repetitive searches. The program then creates an ostream_iterator<cmatch> object, which inserts cmatch objects into its target stream, using the operator<< that the program defined earlier, and passes all three iterators to the standard copy algorithm, which copies the contents of the range defined by [first, last) into the target, out. The tricky code that we had to write in the loop in the previous example is all handled in the regex_iterator's operator++, which is called inside copy.

[2] The type cregex_iterator is a regex_iterator that looks at sequences delineated by char*s.

template <class BidIt,
    class Elem =
      typename iterator_traits<BidIt>::value_type,
    class RXtraits = regex_traits<Elem>>
  class regex_iterator {
public :
  typedef basic_regex<Elem, RXtraits> regex_type;
  typedef match_results<BidIt> value_type;
  typedef std::forward_iterator_tag iterator_category;
  typedef std::ptrdiff_t difference_type;
  typedef const match_results<BidIt> * pointer;
  typedef const match_results<BidIt>& reference;

  regex_iterator(BidIt, BidIt, const regex_type & re,
    regex_constants::match_flag_type =
  regex_iterator(const regex_iterator&);
  regex_iterator & operator = (const regex_iterator&);

  const match_results <BidIt>& operator*();
  const match_results <BidIt> * operator->();

  regex_iterator& operator++();
  regex_iterator operator++(int);

  bool operator==(const regex_iterator&) const;
  bool operator! = (const regex_iterator&) const;

    // exposition only:
  BidIt first, last;
  const regex_type *pre;
  match_flag_type flags;
  match_results <BidIt> match;

The class template describes an object that can serve as a forward iterator for an unmodifiable sequence of character sequences that match a regular expression.

The template argument BidIt must be a bidirectional iterator. It names the type of the iterator that will designate the target character sequence when an iterator object is created. The template arguments Elem and RXtraits name the character type and the traits type, respectively, for the regular expression type, basic_regex<Elem, Rxtraits>, that will be passed to a regex_iterator object's constructor. By default, these arguments are derived from the first type argument, BidIt.

You create a regex_iterator object by passing two iterators that delineate a character range to be searched and a basic_regex object that holds the regular expression to search for. The resulting object points at the first matching subsequence in the target sequence. Each application of operator++ advances the iterator to point at the next matching subsequence, until there are no more matching subsequences. At that point, the iterator compares equal to the end-of-sequence iterator, which is created with the default constructor.

The template defines several nested types (Section 19.2.1) and provides three constructors and an assignment operator (Section 19.2.2). An object can be dereferenced with operator* and operator-> (Section 19.2.3), and can be incremented, to point at the next element in the output sequence, with operator++ (Section 19.2.4). Two regex_iterator objects of the same type can be compared for equality (Section 19.2.5). Four predefined types for the most commonly used character types are described in Section 19.2.6.

The definition of this template includes several members marked as exposition only:. These members are used in the descriptions of some of this template's member functions that follow. Keep in mind that these members aren't required by TR1. The rule is that the member functions have to act as if they were implemented according to the descriptions.

Nested Types

typedef basic_regex <Elem, RXtraits> regex_type;

The type is a synonym for basic_regex<Elem, RXtraits>.

The typedef names the type of the regular expression object that will be used in searches. In most cases the regular expression object traffics in the same element type as the target text, so Elem is simply the value type of the bidirectional iterator type BidIt. For example, if the target text to be searched is going to be designated by a const char*, the regular expression object will ordinarily have type basic_regex<char, regex_traits<char>>. This typedef is especially handy if you prefer qualified id's over using declarations.

Figure. Nested Type Name (regexiter/typename.cpp)

# include <regex>
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <string>

typedef std::string::const_iterator seq_t;
typedef std::tr1::regex_iterator <seq_t> rgxiter;
typedef rgxiter::regex_type rgx_t;
typedef std::tr1::match_results <seq_t> match_t;

namespace std { // add inserter to namespace std
template <class Elem, class Alloc>
std::basic_ostream <Elem,  Alloc>& operator <<(
  std::basic_ostream <Elem, Alloc>&  out,
  const match_t & val)
  { // insert cmatch object into stream
  static std::string  empty ("[ empty ]");
  return out << (val.length () ? val.str () : empty);

int main()
  { // split out words from text file
  rgx_t rgx ("[[: alnum :]_#]+ ");
  ifstream input (" typename .cpp ");
  std::string  str;
  while (std::getline (input, str))
    { // split out words from a line of text
    rgxiter first (str.begin (), str .end (), rgx), last;
    std::ostream_iterator <rgxiter::value_type>
      tgt (std::cout, "\n"));
    std::copy (first, last, tgt);
  return 0;

typedef match_results <BidIt>  value_type;
typedef std::forward_iterator_tag  iterator_category;
typedef std::ptrdiff_t  difference_type;
typedef const match_results <BidIt>* pointer;
typedef const match_results <BidIt>& reference;

These are the usual typedefs for an iterator type.

Constructing and Assigning

regex_iterator <BidIt, Elem, RXtraits>::regex_iterator ();

The constructor constructs an end-of-sequence iterator.

regex_iterator <BidIt, Elem,   RXtraits>::regex_iterator (
  BidIt first1, BidIt last1,
  const regex_type & re,
  regex_constants::match_flag_type flgs =

The constructor constructs an object with initial values first and last equal to first1 and last1, respectively; pre equal to &re;[3] and flags equal to flgs. The constructor then calls regex_search(first, last, match, *pre, flags); if that call returns false, it marks the object as an end-of-sequence iterator.

[3] Note that the iterator holds the address of the regular expression object, not a copy. Once the regular expression object is destroyed, the iterator can no longer be used.

In other words, the constructor stores the various search parameters, then searches for the first occurrence of text matching re in the range of characters pointed at by [first1, last1). If the search succeeds, the result is stored in the member data object match. If the search fails, there are no matches, and the object is marked as an end-of-sequence iterator, that is, an object that compares equal to a default-constructed object.

Figure. End-of-Sequence (regexiter/endofsequence.cpp)

#include <regex>
#include <string>
#include <iostream>
using std::string ; using std::cout;
typedef string::const_iterator seq_t;
typedef std::tr1::regex_iterator <seq_t> rgxiter;
typedef rgxiter::regex_type rgx_t;

int main()
  { // constructing regex iterator objects
  rgx_t rgx ("not found ");
  string target (" this is text ");
  rgxiter first (target.begin (), target.end (), rgx);
  rgxiter last;
  if (first ==  last)
    cout << " regular expression not found \n";
    return 0;

regex_iterator <BidIt, Elem, RXtraits>::regex_iterator (
  const regex_iterator & right);
regex_iterator &
  regex_iterator <BidIt, Elem, RXtraits>::operator= (
  const regex_iterator & right);

The copy constructor and the assignment operator copy their argument into *this. After the operation, *this == right.


const match_results <BidIt>&
  regex_iterator <BidIt,  Elem, RXtraits>::operator* () const;
const match_results <BidIt>*
  regex_iterator <BidIt,  Elem, RXtraits>::operator-> () const;

The behavior of a program that calls either of these member operators on an end-of-sequence iterator is undefined. Otherwise, the first member operator returns a reference to the contained object match, and the second member operator returns a pointer to the contained object match.

The contained object match holds the results of the most recent successful search, so you can use these operators to look at those results, just as if you had written a call to regex_search yourself and passed a match_results object.

Figure. Examining Search Results (regexiter/result.cpp)

#include <regex>
#include <iostream>
#include <iomanip>
#include <string>
using std::string; using std::cout; using std::setw;

typedef string:: const_iterator  seq_t;
typedef std::tr1::regex_iterator <seq_t> rgxiter;
typedef rgxiter:: regex_type  rgx_t;
typedef rgxiter:: value_type  match_t;

static void show (const match_t & match)
  { // show contents of match_t object
  for (int idx = 0; idx <match.size (); ++ idx)
    { // show match[idx]
    cout << idx << ": ";
    if (match [ idx ]. matched)
      cout << setw (match.position(idx)) << ""
        << match.str(idx) << '\n';
      cout << "[not matched]";

int main()
  { // demonstrate regex  iterator dereferencing
  string id =
    " ([[: alpha :]]+)([[: space :]]+)([[: digit :]]{2,5}) ";
  rgx_t model_descr (id);
  string item ("Emperor 400");
  rgxiter iter (item.begin (), item.end (), model_descr);
  show (*iter);                                       // operator*
  cout << iter->str () < < '\n';  // operator->
  return 0;


  regex_iterator <BidIt, Elem, RXtraits>::operator++ (int)
    { regex_iterator tmp (* this); ++* this ; return tmp ;  }
regex_iterator &
  regex_iterator <BidIt, Elem, RXtraits>::operator++ ();

The first member function makes a copy of *this, increments *this, and returns the copy.

The second member function begins by constructing a local variable referred to here as start, initialized with the value match[0].second.

If match.length() == 0 and start == end, it marks the object as an end-of-sequence iterator and returns *this.

Otherwise, if match.length() == 0, the operator creates a temporary object, temp_flags, of type match_flag_type, holding the value flags | match_not_null | match_continuous. It then calls regex_search(start, last, match, *pre, temp_flags). If the call returns true, the operator returns *this. Otherwise, it increments start and moves to the following step.

The operator next sets flags to flags | match_prev_avail and calls regex_search(start, last, match, *pre, flags). If the call returns false, the operator marks the object as an end-of-sequence iterator. The call returns *this.

Whenever a call to regex_search returns TRue, the operator adjusts the contents of match so that match.prefix().first is equal to the previous value of match[0].second; for each value of idx for which match[idx]. matched is true, match[idx].position() returns the value of distance(begin, match[idx].first).

You probably recognized most of this text as a description of the repetitive search algorithm we developed in Section 19.1. But, the last paragraph adds a twist: Regardless of how it got there, the prefix after a successful search is the text from the end of the previous successful match up to the current match, and all the match positions are offsets from the start of the original text sequence.

Look at how the output showing the various matches is formatted in this example, which is similar to the previous one.

Figure. Incrementing (regexiter/increment.cpp)

#include <regex>
#include <iostream>
#include <iomanip>
#include <string>
using std::string; using std::cout; using std::setw;

typedef string:: const_iterator seq_t;
typedef std::tr1::regex_iterator <seq_t> rgxiter;
typedef rgxiter:: regex_type rgx_t;
typedef rgxiter:: value_type match_t;

static void show(const match_t & match)
  { // show contents of  match_t object
  for (int idx = 0; idx <match.size(); ++idx)
    { // show match[idx]
    cout << idx << ": ";
    if (match[idx]. matched)
      cout << setw (match.position (idx)) << ""
        << match.str (idx) << '\n';
      cout << "[not matched]";

int main()
  { // demonstrate regex_iterator dereferencing
  string id =
    " ([[:alpha:]]+)([[:space:]]+)([[:digit:]]{2,5}) ";
  rgx_t   model_descr (id);
  string item ("Emperor 280, Emperor 400, Whisper 60 ");
  rgxiter first (item.begin(), item.end(), model_descr);
  rgxiter last;
  cout << "  " << item <<'\n';
  while (first !=last)
    show (* first ++);
  return 0;


bool regex_iterator<BidIt, Elem, RXtraits>::operator==(
  const regex_iterator& right) const;
bool regex_iterator<BidIt, Elem, RXtraits>::operator!=(
  const regex_iterator& right) const
  { return !(*this == right); }

The first member operator returns true only if *this and right are both end-of-sequence iterators or if first == right.first, last == right. last, pre == right.pre, flags == right.flags, and match == right .match. The second member operator returns !(*this == right).

This rather lengthy description says what you'd expect: If you create two regex_iterator objects with the same arguments or by copying one onto the other, they compare equal. If you increment two equal iterators the same number of times, they still compare equal. As long as the searcheseither at construction or as part of an incrementsucceed, the object does not compare equal to an end-of-sequence iterator. When a search fails, as we saw earlier, the iterator object is marked as an end-of-sequence iterator; at that point, it compares equal to any other end-of-sequence iterator.

Figure. Comparing (regexiter/compare.cpp)

# include <regex>
#include <iostream>
#include <string>
using std::tr1::regex; using std::tr1::regex_iterator;
using std::string; using std::cout;

typedef regex_iterator<string::const_iterator> iter_t;

static void show_equal(const char *title,
  const iter_t& iter0, const iter_t& iter1)
  { // show equality of iterator objects
  cout << title << "\n"
    << (iter0 == iter1? "equal" : "not equal") << '\n';

int main()
  {   // demonstrate regex iterator comparison operators
  regex rgx0("abc"), rgx1("abc");
  string tgt0("abc"), tgt1("abc");
  iter_t iter0(tgt0.begin(), tgt0.end(), rgx0);
  iter_t iter1(tgt0.begin(), tgt0.end(), rgx1);
    "same range, different regular expression objects",
    iter0, iter1);
  iter_t iter2(tgt0.begin() + 1, tgt0.end(), rgx0);
    "different range, same regular expression objects",
    iter0, iter2);
  iter_t iter3, iter4;
  show_equal("default constructed",
    iter3, iter4);
    "non-default constructed and default constructed",
    iter0, iter4);
  ++iter0;  // move past final match
    "incremented to end and default constructed",
    iter0, iter4);
  return 0;

19.2.6. Predefined regex_iterator Types

typedef regex_iterator<const char*>
typedef regex_iterator<const wchar_t*>
typedef regex_iterator<string::const_iterator>
typedef regex_iterator<wstring::const_iterator>

As always, there are four predefined regex_iterator types for text sequences held in arrays of char and wchar_t and in basic_string objects holding elements of type char and wchar_t.

 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows