match_results operator= in C++

The match_results::operator= is used to replace all the matches in a smatch object with new matches from another smatch object.

Syntax:

smatch_name1 = (smatch_name2)

Note: smatch_name is an object of match_results class.

Parameters: The smatch object on the right side gets copied to the one at the left side.



Return Value: It does not return anything.

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:

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 match1, match2;
  
    regex_match(s, match1, re);
  
    // use of operator =--> assigns all
    // the contents of match1 to match2
    match2 = match1;
  
    cout << "Matches are:" << endl;
    for (smatch::iterator it = match2.begin();
         it != match2.end(); it++) {
        cout << *it << endl;
    }
}

chevron_right


Output:

Matches are:
Geeksforgeeks
Geeks
forgeeks

Program 2:

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 re1("(Geeks)(.*)");
    regex re2("(Ge)(eks)(.*)");
  
    smatch match1, match2;
  
    regex_match(s, match1, re1);
    regex_match(s, match2, re2);
  
    smatch max_match;
  
    // use of operator =--> assigns all
    // the contents of match1 to match2
    if (match1.size() > match2.size()) {
        max_match = match1;
    }
    else {
        max_match = match2;
    }
  
    cout << "Smatch with maximum matches:" << endl;
    for (smatch::iterator it = max_match.begin();
         it != max_match.end(); it++) {
        cout << *it << endl;
    }
}

chevron_right


Output:

Smatch with maximum matches:
Geeksforgeeks
Ge
eks
forgeeks


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.