- 19.1 Brute-Force Searches
- 19.2 The <tt>regex_iterator</tt> Class Template
- 19.3 The <tt>regex_token_iterator</tt> Class Template
- Exercises
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.