Open In App

match_results empty() in C++ STL

Improve
Improve
Like Article
Like
Save
Share
Report

The match_results::empty() is a inbuilt function in C++ which returns True if the smatch object contains no matches.
Syntax: 
 

smatch_name.empty()

Note: smatch_name is an object of match_results class.

Parameters:This function accept no parameters.
Return value: This function returns true when the object is default-constructed or else return false if any of the regex_match or regex_search finds atleast one match.
Errors and Exceptions: 
 

  • It has no exception throw guarantee.
  • Throws exception when a parameter is passed.

Note: First element always contains the whole regex match while the others contain the particular Capturing Group.
Below programs illustrate the above method. 
Program 1: 
 

CPP




// CPP program to illustrate
// match_results empty() in C++
#include<bits/stdc++.h>
using namespace std;
 
int main()
{
    string s("harsha");
    regex re1("Geeks.*");
    regex re2("geeks.*");
 
    smatch match1, match2;
 
    regex_match(s, match1, re1);
    regex_match(s, match2, re2);
 
    // if match1 is empty it returns
    // true or else false
    if (match1.empty()) {
        cout << "Regex-1 did not match" << endl;
    }
    else {
        cout << "Regex-1 matched" << endl;
    }
 
    // if match2 is empty it returns
    // true or else false
    if (match2.empty()) {
        cout << "Regex-2 did not match" << endl;
    }
    else {
        cout << "Regex-2 matched" << endl;
    }
 
    return 0;
}


Output: 

Regex-1 did not match
Regex-2 did not match

 

Program 2: 
 

CPP




// CPP program to illustrate
// match_results empty() in C++
#include<bits/stdc++.h>
using namespace std;
 
int main()
{
    string s("geeksforgeeks");
    regex re1("Geeks.*");
    regex re2("geeks.*");
 
    smatch match1, match2;
 
    regex_match(s, match1, re1);
    regex_match(s, match2, re2);
 
    // if match1 is empty it returns
    // true or else false
    if (match1.empty()) {
        cout << "Regex-1 did not match" << endl;
    }
    else {
        cout << "Regex-1 matched" << endl;
    }
 
    // if match2 is empty it returns
    // true or else false
    if (match2.empty()) {
        cout << "Regex-2 did not match" << endl;
    }
    else {
        cout << "Regex-2 matched" << endl;
    }
 
    return 0;
}


Output: 

Regex-1 did not match
Regex-2 matched

 



Last Updated : 21 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads