regex_iterator() function in C++ STL

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

#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;
    }
}

chevron_right


Output:

Trying to find words using regex_iterator:

Number of words found: 3

The words are:
Geeksforgeeks
welcome
geeks.


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.