match_results operator= in C++
Last Updated :
21 Jun, 2021
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 contain the particular Capturing Group.
Below programs illustrate the above function.
Program 1:
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s( "Geeksforgeeks" );
regex re( "(Geeks)(.*)" );
smatch match1, match2;
regex_match(s, match1, re);
match2 = match1;
cout << "Matches are:" << endl;
for (smatch::iterator it = match2.begin();
it != match2.end(); it++) {
cout << *it << endl;
}
}
|
Output:
Matches are:
Geeksforgeeks
Geeks
forgeeks
Program 2:
CPP
#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;
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;
}
}
|
Output:
Smatch with maximum matches:
Geeksforgeeks
Ge
eks
forgeeks
Share your thoughts in the comments
Please Login to comment...