match_results prefix() and suffix() in C++

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of match_results::prefix() and match_results::suffix() functions 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:: prefix()?

match_results::prefix() function is an inbuilt function in C++ STL, which is defined in <regex> header file. prefix() is used to get the preceding match_results of the object associated with the function. This function returns the reference of the succeeding sequence of the match_results object.

Syntax

match_results.prefix();

Parameters

This function accepts no parameter.

Return value

This function returns constant reference of the string or sequence preceding the match sequence.

Example

Input: string str = "Tutorials Points";
   regex R("Points");
   smatch Mat;
   regex_search(str, Mat, R);
   Mat.prefix();
Output: Tutorials

prefix()

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   string str = "Tutorials Points";
   regex R("Points");
   smatch Mat;
   regex_search(str, Mat, R);
   cout<<"String prefix is : ";
   if (!Mat.empty()) {
      cout << Mat.prefix();
   }
   return 0;
}

Output

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

String prefix is : Tutorials

What is match_results:: suffix()?

match_results::suffix() function is an inbuilt function in C++ STL, which is defined in <regex> header file. suffix() is used to get the succeeding match_results of the object associated with the function. This function returns the reference of the succeeding sequence of the match_results object.

Syntax

match_results.suffix();

Parameters

This function accepts no parameter.

Return value

This function returns constant reference of the string or sequence succeeding the match sequence.

Example

Input: std::string str("Tutorials Points is the best");
   std::smatch Mat;
   std::regex re("Points");
   std::regex_match ( str, Mat, re );
   Mat.suffix();
Output: is the best

suffix()

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   string str = "Tutorials Points is the best";
   regex R("Points");
   smatch Mat;
   regex_search(str, Mat, R);
   cout<<"String prefix is : ";
   if (!Mat.empty()) {
      cout << Mat.suffix();
   }
   return 0;
}

Output

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

String prefix is : is the best
raja
Published on 23-Mar-2020 06:45:12
Advertisements