Skip to content
Related Articles

Related Articles

match_results length() in C++ STL
  • Last Updated : 04 Sep, 2018

The match_results::length() is a inbuilt function in C++ which is used to return the length of a particular match in the match_results object.

Syntax:

smatch_name.length(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 length of the n-th match in the match_results object.

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



Below programs illustrate the above function.

Program 1:




// CPP program to illustrate
// match_results length() in C++
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    string s("Geeksforgeeks");
    regex re("(Geeks)(.*)");
  
    smatch match;
  
    regex_match(s, match, re);
  
    for (int i = 0; i < match.size(); i++) {
        cout << "match " << i << " has a length of "
             << match.length(i) << endl;
    }
    return 0;
}
Output:
match 0 has a length of 13
match 1 has a length of 5
match 2 has a length of 8

Program 2:




// CPP program to illustrate
// match_results length() in C++
#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;
    return 0;
}
Output:
max-length sub match is forgeeks with a length of 8
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :