Open In App

regex_iterator() function in C++ STL

Last Updated : 26 Oct, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

regex_iterator() is a function from the BiDirectionalIterator class in C++. This method returns an iterator type to iterate over different matches of a same regex pattern in a sequence.

Syntax:

template<
    class BidirectionalIterator,
    class CharT = typename std::iterator_traits::value_type,
    class Traits = std::regex_traits > class regex_iterator

C++14 Syntax

template <class BidirectionalIterator,
          class charT=typename iterator_traits::value_type,
          class traits=regex_traits > class regex_iterator;

C++11 Syntax:

template <class BidirectionalIterator,
          class charT=typename iterator_traits::value_type,
          class traits=regex_traits > class regex_iterator;

Parameters: This method accepts following parameters:

  • BidirectionalIterator: Which iterates on the target sequence of characters.
  • CharT: It is a type char.
  • traits: It is the regex traits type.

Return Value: This method returns a string object with the resulting sequence.

Below examples illustrate the regex_iterator() method:

Example:




#include <iostream>
#include <iterator>
#include <regex>
#include <string>
using namespace std;
  
int main()
{
    const string
        strg
        = "Geeksforgeeks welcome geeks.";
  
    regex words_regex("[^\\s]+");
    auto
        words_begin
        = sregex_iterator(
            strg.begin(),
            strg.end(),
            words_regex);
  
    auto words_end = sregex_iterator();
  
    cout << "Trying to find words"
         << " using regex_iterator:\n\n";
  
    cout << "Number of words found: "
         << distance(words_begin, words_end);
  
    cout << "\n\nThe words are:\n";
    for (sregex_iterator k = words_begin;
         k != words_end;
         ++k) {
  
        smatch match = *k;
        string match_str = match.str();
  
        cout << match_str
             << endl;
    }
}


Output:

Trying to find words using regex_iterator:

Number of words found: 3

The words are:
Geeksforgeeks
welcome
geeks.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads