Home > Articles > Programming > C/C++

This chapter is from the book

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*>
  cregex_iterator;
typedef regex_iterator <const wchar_t*>
  wcregex_iterator;
typedef regex_iterator <string::const_iterator>
  sregex_iterator;
typedef regex_iterator <wstring::const_iterator>
  wsregex_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.

Example 19.9. 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.

template <class BidIt,
    class Elem =
      typename iterator_traits<BidIt>::value_type,
    class RXtraits = regex_traits<Elem>>
  class regex_iterator {
public :
    // NESTED TYPES
  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;

    // CONSTRUCTING AND ASSIGNING
  
   regex_iterator();
  regex_iterator(BidIt, BidIt, const regex_type & re,
    regex_constants::match_flag_type =
      regex_constants::match_default);
  regex_iterator(const regex_iterator&);
  regex_iterator & operator = (const regex_iterator&);

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

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

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

private:
    // 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.

19.2.1 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.

Example 19.10. 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.

19.2.2 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 =
    regex_constants::match_default);

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.

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.

Example 19.11. 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.

19.2.3 Dereferencing

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.

Example 19.12. 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';
    else
      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;
  }

19.2.4 Modifying

regex_iterator
  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.

Example 19.13. 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';
    else
      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;
  }

19.2.5 Comparing

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 searches—either at construction or as part of an increment—succeed, 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.

Example 19.14. 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);
  show_equal(
    "same range, different regular expression objects",
    iter0, iter1);
  iter_t iter2(tgt0.begin() + 1, tgt0.end(), rgx0);
  show_equal(
    "different range, same regular expression objects",
    iter0, iter2);
  iter_t iter3, iter4;
  show_equal("default constructed",
    iter3, iter4);
  show_equal(
    "non-default constructed and default constructed",
    iter0, iter4);
  ++iter0;  // move past final match
  show_equal(
    "incremented to end and default constructed",
    iter0, iter4);
  return 0;
  }

19.2.6 Predefined regex_iterator Types

typedef regex_iterator<const char*>
  cregex_iterator;
typedef regex_iterator<const wchar_t*>
  wcregex_iterator;
typedef regex_iterator<string::const_iterator>
  sregex_iterator;
typedef regex_iterator<wstring::const_iterator>
  wsregex_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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020