match_results operator[] in C++ STL

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of match_results operator ‘[ ]’ in C++ STL.

What is a match_results in C++ STL?

std::match_results is a specialized container-like class which is used to hold the collection of character sequences which are matched. In this container class a regex match operation finds the matches of the target sequence.

What is match_results operator ‘[ ]’

Match_results operator [] is a reference operator which is used to directly refer to i-th position of a match_results. Operator [] returns i-th match position of the object associated. This operator comes in handy when we have to directly access the element by its match position starting from zero.

Syntax

match_results1[int i];

Parameters

This operator takes 1 parameter of integral type i.e. of the element we want to access.

Return value

This function returns the reference to the i-th location of the match result.

Example

Input: string str = "TutorialsPoint";
   regex R("(Tutorials)(.*)");
   smatch Mat;
   regex_match(str, Mat, R);
   Mat[0];
Output: TutorialsPoint

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   string str = "TutorialsPoint";
   regex R("(Tutorials)(.*)");
   smatch Mat;
   regex_match(str, Mat, R);
   for (int i = 0; i < Mat.size(); i++) {
      cout<<"Match is : " << Mat[i]<< endl;
   }
   return 0;
}

Output

If we run the above code it will generate the following output −

Match is : TutorialsPoint
Match is : Tutorials
Match is : Point

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   string str = "Tutorials Point";
   regex R("(Tutorials)(Point)(.*)");
   smatch Mat;
   regex_match(str, Mat, R);
   int len = 0;
   string S;
   for(int i = 1; i < Mat.size(); i++) {
      if (Mat.length(i) > len) {
         str = Mat[i];
         len = Mat.length(i);
      }
   }
   cout<<"Matching length is : " << len<< endl;
   return 0;
}

Output

If we run the above code it will generate the following output −

Matching length is : 0
raja
Published on 23-Mar-2020 11:11:59
Advertisements