match_results operator[] in C++ STL

The match_results::operator[] is a built function in C++ which used to get the i-th match in the match_result object. It gives the reference to the match at the position given inside the operator.

Syntax:

smatch_name[N]

Note: smatch_name is an object of match_results class.

Parameters: It accepts a single parameter N which specifies the Match number. It is lower than match_results::size. The match number 0 represents the entire matched expression. Subsequent match numbers identify the sub-expressions if any. The passed integral is an unsigned integral type.

Return value: It returns the direct reference to the match at the N-th match.

Note: First element always contains the whole regex match while the others conatain the particular Capturing Group.



Below programs illustrates the above function.
Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to illustrate
// match_results operator[] in C++
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    string s("Geeksforgeeks");
    regex re("(Geeks)(.*)");
  
    smatch match;
  
    regex_match(s, match, re);
  
    // use of operator[]--> returns the
    // reference to the match at i-th position
    cout << "Matches are:" << endl;
    for (int i = 0; i < match.size(); i++) {
        cout << "match " << i << " is " << match[i] << endl;
    }
}

chevron_right


Output:

Matches are:
match 0 is Geeksforgeeks
match 1 is Geeks
match 2 is forgeeks

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to illustrate
// match_results operator[] in C++
// Find maximum length 
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    string s("Geeksforgeeks");
    regex re("(Ge)(eks)(.*)");
  
    smatch match;
  
    regex_match(s, match, re);
  
    int max_length = 0;
    string str;
  
    // Since the first match is the whole string we do not consider it.
    for (int i = 1; i < match.size(); i++) {
        if (match.length(i) > max_length) {
            str = match[i];
            max_length = match.length(i);
        }
    }
  
    cout << "max-length sub match is " << str 
         << " with a length of " << max_length << endl;
    return 0;
}

chevron_right


Output:

max-length sub match is forgeeks with a length of 8


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.