Home > Articles > Programming > C/C++

This chapter is from the book

19.3 The regex_token_iterator Class Template

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

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

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

typedef regex_token_iterator<const char*>
  cregex_token_iterator;
typedef regex_token_iterator<const wchar_t*>
  wcregex_token_iterator;
typedef regex_token_iterator<string::const_iterator>
  sregex_token_iterator;
typedef regex_token_iterator<wstring::const_iterator>
  wsregex_token_iterator;

} }

Dereferencing a regex_iterator object produces a match_results object that represents the current match. As we saw in several earlier examples, the returned object can, in turn, be used to get at various submatches of a successful match. A regex_token_iterator object provides direct access to submatches. When you construct a regex_token_iterator object, you pass an additional set of numeric arguments that designate the desired submatches. Each time you increment the iterator, it advances to the next submatch. When it runs out of submatches, the iterator moves to the next match and starts the list of submatches over again. So the explicit loop over submatches that we used earlier can be eliminated.

Example 19.15. Searching(regexiter/tokiterator.cpp)

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

typedef string::const_iterator seq_t;
typedef std::tr1::regex_token_iterator<seq_t> rgxiter;
typedef rgxiter::regex_type rgx_t;
typedef rgxiter::value_type match;

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

This program is much simpler than the similar one in Section 19.2.4 but doesn't provide as much information. That's because operator* on a regex_-token_iterator object returns a sub_match object, which points at a portion of the target text and, unlike match_results, does not know how far into the target text this match occurred.

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

    // CONSTRUCTING AND ASSIGNING
  
  regex_token_iterator();
  regex_token_iterator(BidIt first, BidIt last,
    const regex_type& re, int submatch = 0,
    regex_constants::match_flag_type flags =
      regex_constants::match_default);
  regex_token_iterator(BidIt first, BidIt last,
    const regex_type& re,
    const std::vector<int> submatches,
    regex_constants::match_flag_type flags =
      regex_constants::match_default);
  template<std::size_t N>
  regex_token_iterator(BidIt first, BidIt last,
    const regex_type& re, const int(&submatches)[N],
    regex_constants::match_flag_type flags =
      regex_constants::match_default);
  regex_token_iterator(const regex_token_iterator&);
  regex_token_iterator& operator=(
    const regex_token_iterator&);

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

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

    // COMPARING
  bool operator==(const regex_token_iterator& right) const;
  bool operator!=(const regex_token_iterator& right) const;

private:
  // exposition only:
  typedef regex_iterator<BidIt, Elem, RXtraits> iter;
  iter pos;
  std::vector <int> subs;
  std::size_t N;
  };

The class template describes an object that can serve as a forward iterator for an unmodifiable sequence of character sequences that match various parts of 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_token_iterator object's constructor. By default, these arguments are derived from the first type argument, BidIt.

You create a regex_token_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, just as you do for a regex_iterator object. In addition, though, you pass one or more integer values that identify the various submatches that you want to iterate through. The constructors search for the first text subsequence that matches the regular expression. The resulting object points at the first of the designated submatches in the matching subsequence. Each application of operator++ moves to the next submatch. If the list of submatches has been exhausted, the operator searches for the next text subsequence that matches the regular expression and points at the first of the designated submatches in the matching subsequence. If there are no more matching subsequences, 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.3.1) and provides five constructors and an assignment operator(Section 19.3.2). An object can be dereferenced with operator* and operator->(Section 19.3.3) and can be incremented to point at the next element in the output sequence with operator++(Section 19.3.4). Two regex_token_iterator objects of the same type can be compared for equality(Section 19.3.5). Four predefined types for the most commonly used character types are described in Section 19.3.6.

The definition of this template includes several members marked as exposition only:. These members are used in the descriptions that follow of some of the member functions of this template. 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.

The descriptions also use a couple of technical terms that are defined in TR1. A suffix iterator is an iterator object of type regex_token_iterator that points at the final sequence of characters in the target text. The current match is (*pos).prefix() if subs[N] is -1; otherwise, (*pos)[subs[N]].

That last term is the key to understanding how a regex_token_iterator determines the sequence of submatches to return. When you construct a regex_token_iterator object, you pass one or more integer values, as described in Section 19.3.2. Those values, in turn, determine which submatches will be returned and in what order. A value of -1 refers to the text beginning at the end of the previous match—or at the beginning of the text sequence when the iterator object is first constructed—and ending at the beginning of the current match. After the final, failed, search, a value of -1 refers to the text from the end of the last successful search—or the beginning of the text sequence if no search succeeded—to the end of the text sequence. Any other value refers to the corresponding capture group. Thus, a value of 0 means the entire matched text, a value of 1 means the first capture group, and so on. Each time you increment an iterator object, it advances to the next subgroup, as determined by those integer values. When it's gone through all those values, it moves to the next match and repeats the sequence of values.

19.3.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. For details, see the discussion in Section 19.2.1.

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

These are the usual typedefs for an iterator type.

19.3.2 Constructing and Assigning

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

The constructor constructs an end-of-sequence iterator.

regex_token_iterator<BidIt, Elem, RXtraits>::
  regex_token_iterator(
  BidIt first, BidIt last,
  const regex_type& re, int submatch = 0,
  regex_constants::match_flag_type flags =
    regex_constants::match_default);
regex_token_iterator<BidIt, Elem, RXtraits>::
  regex_token_iterator(
  BidIt first, BidIt last,
  const regex_type& re,
  const std::vector<int> submatches,
  regex_constants::match_flag_type flags =
    regex_constants::match_default);
template<std::size_t N>
regex_token_iterator<BidIt, Elem, RXtraits>::
  regex_token_iterator(
  BidIt first, BidIt last,
  const regex_type& re, const int (&submatches)[N],
  regex_constants::match_flag_type flags =
    regex_constants::match_default);

The first constructor stores the value of submatch in subs. The second and third constructors each copy their argument submatch into subs.

The constructors then set the value of N to 0 and the value of pos to iter(first, last, re, flags). If pos is not an end-of-sequence iterator, the constructors set res to the address of the current match. Otherwise, if any of the values stored in subs is -1, the constructors set *this to be a suffix iterator that points at the entire text sequence [first, last). Otherwise, the constructors set *this to an end-of-sequence iterator.

The first constructor takes exactly one integer argument, which designates the sub-group to be returned by the iterator. To see the entire matching text, pass the value 0. To see the nth capture group, pass n. To see the text that precedes the match, pass -1.

Example 19.16. Viewing a Single Submatch(regexiter/single.cpp)

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

typedef string::const_iterator seq_t;
typedef std::tr1::regex_token_iterator<seq_t> rgxiter;
typedef rgxiter::regex_type rgx_t;
typedef rgxiter::value_type match;

static void show(int field)
  {   // demonstrate single-field constructor
  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, field);
  rgxiter last;
  while (first != last)
    cout << *first++ << '\n';
  }
int main()
  {  // demonstrate regex_token_iterator single-field constructor
  cout << "Full match:\n";
  show(0);
  cout << "\nModel name:\n";
  show(1);
  cout << "\nModel number:\n";
  show(3);
  cout << "\nSeparators :\n";
  show(-1);
  return 0;
  }

The second and third constructors take one or more integer arguments, either as a C++ vector<int> or as a C-style array of int.

Example 19.17. Viewing Multiple Submatches(regexiter/multiple.cpp)

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

typedef string::const_iterator seq_t;
typedef std::tr1::regex_token_iterator<seq_t> rgxiter;
typedef rgxiter::regex_type rgx_t;
typedef rgxiter::value_type match;

static void show(const vector <int>&, fields)
  { // demonstrate multiple-field constructor
  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, fields);
  rgxiter last;
  while(first != last)
    cout << *first++ << '\n';
  }
int main()
  { // demonstrate regex_token_iterator multiple-field constructor
  vector<int> fields;
  fields.push_back(0);
  cout <<"Full match:\n";
  show(fields);
  fields.push_back(3);
  cout <<"Full match, model number:\n";
  show(fields);
  fields.push_back(1);
  cout <<" Full match, model number,  model name :\n";
  show(fields);
  return 0;
  }
regex_token_iterator<BidIt,  Elem, RXtraits>::
  regex_token_iterator(
  const regex_token_iterator& right);
regex_token_iterator&
regex_token_iterator<BidIt,  Elem, RXtraits>::
  operator=(
  const regex_token_iterator& right);

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

19.3.3 Dereferencing

const basic_string <Elem>&
  regex_token_iterator<BidIt, Elem, RXtraits>::
  operator*() const;
const basic_string <Elem>*
  regex_token_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 current match, and the second member operator returns a pointer to the current match.

19.3.4 Modifying

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

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

If the stored iterator pos is an end-of-sequence iterator, the second operator marks *this as an end-of-sequence iterator. Otherwise, the operator increments the stored value N; if the result is equal to subs.size(), it sets the stored value N to 0 and increments the stored iterator pos. If incrementing the stored iterator leaves it unequal to an end-of-sequence iterator, the operator does nothing further. Otherwise, if the end of the preceding match was at the end of the character sequence, the operator marks *this as an end-of-sequence iterator. Otherwise, the operator repeatedly increments the stored value N until N == subs.size(), in which case it marks *this as an end-of-sequence iterator or until subs[N] == -1, thus ensuring that the next dereference will return the suffix of the last successful match. In all cases, the operator returns *this.

To better understand how a submatch selector of -1 works, think of the target text as a sequence of subsequences U 1 M 1 U 2 M 2 ... U m M m U m + 1, where the various subsequences M i match the regular expression, and the various subsequences U i do not match the regular expression. A selector of -1 selects the U i subsequences, including the final nonmatching subsequence U m + 1 if it is not empty.

Example 19.18. Selecting Separators(regexiter/select.cpp)

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

typedef string::const_iterator seq_t;
typedef std::tr1::regex_token_iterator<seq_t> rgxiter;
typedef rgxiter::regex_type rgx_t;
typedef rgxiter::value_type match;

int main()
  { // demonstrate use of selector value -1
  string csv(" [[: space :]]*,[[: space :]]*");
  rgx_t rgx(csv);
  string data(" Ron   Mars,   2114 East St .,   Biloxi, MI");
  rgxiter first(data.begin(), data .end(), rgx,   -1);
  rgxiter last;
  while(first !=  last)
    cout <<*first++ << '\n';
  return 0;
  }

19.3.5 Comparing

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

The first member function returns true if *this and right are both end-of-sequence iterators or if both are suffix iterators that point at the same text sequence. Otherwise, if either of them is an end-of-sequence iterator or a suffix iterator, the member function returns false. Otherwise, the member function returns pos == right.pos&& subs == right.subs&& N == right.N.

The second member function returns !(*this == right).

Two regex_token_iterator objects compare equal if they were constructed from the same regular expression argument and equal other arguments, and they have been incremented the same number of times. When you make a copy of a regex_token_iterator object, the first requirement is obviously satisfied, so a copy of a regex_token_iterator object is equal to the object it was copied from if both have been incremented the same number of times since the copy was made.

Example 19.19. Comparing(regexiter/comparetok.cpp)

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

typedef string::const_iterator siter;
typedef regex_token_iterator<siter> 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_token_iterator comparison operators
  string csv(" [[: space :]]*,[[: space :]]*");
  regex rgx(csv);
  string data(" Ron Mars,  2114 East St ., Biloxi, MI");
  int selector0 [] = { 0, 1 };
  int selector1 [] = { 0, 1 };
  int selector2 [] = { 1, 0 };
  iter_t iter0(data.begin(), data.end(), rgx, selector0);
  iter_t iter1(data.begin(), data.end(), rgx, selector0);
  show_equal("equal arguments", iter0, iter1);
  iter_t iter2(data.begin(), data.end(), rgx, selector1);
  show_equal("equal selectors", iter0, iter2);
  iter_t iter3(data.begin(), data.end(), rgx, selector2);
  show_equal("unequal selectors", iter0, iter3);

  iter_t iter4(++ iter0);
  show_equal("copy", iter0, iter4);
  ++ iter0;
  show_equal("unequal increments", iter0, iter4);
  ++ iter4;
  show_equal("equal increments", iter0, iter4);
  return 0;
  }

19.3.6 Predefined regex_token_iterator Types

typedef regex_token_iterator<const char *>
  cregex_token_iterator;
typedef   regex_token_iterator<const wchar_t *>
  wcregex_token_iterator;
typedef   regex_token_iterator<string::const_iterator>
  sregex_token_iterator;
typedef   regex_token_iterator<wstring::const_iterator>
  wsregex_token_iterator;

As always, there are four predefined regex_token_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