Regex is the short form for “Regular expression”, which is often used in this way in programming languages and many different libraries. It is supported in C++11 onward compilers.
Function Templates used in regex
regex_match() -This function return true if the regular expression is a match against the given string otherwise it returns false.
CPP
#include <iostream>
#include <regex>
using namespace std;
int main()
{
string a = "GeeksForGeeks" ;
regex b( "(Geek)(.*)" );
if ( regex_match(a, b) )
cout << "String 'a' matches regular expression 'b' \n" ;
if ( regex_match(a.begin(), a.end(), b) )
cout << "String 'a' matches with regular expression "
"'b' in the range from 0 to string end\n" ;
return 0;
}
|
Output
String 'a' matches regular expression 'b'
String 'a' matches with regular expression 'b' in the range from 0 to string end
regex_search() – This function is used to search for a pattern matching the regular expression
CPP
#include <iostream>
#include <regex>
#include<string.h>
using namespace std;
int main()
{
string s = "I am looking for GeeksForGeeks "
"articles" ;
regex r( "Geek[a-zA-Z]+" );
smatch m;
regex_search(s, m, r);
for ( auto x : m)
cout << x << " " ;
return 0;
}
|
regex_replace() This function is used to replace the pattern matching to the regular expression with a string.
CPP
#include <iostream>
#include <string>
#include <regex>
#include <iterator>
using namespace std;
int main()
{
string s = "I am looking for GeeksForGeek \n" ;
regex r( "Geek[a-zA-z]+" );
cout << std::regex_replace(s, r, "geek" );
string result;
regex_replace(back_inserter(result), s.begin(), s.end(),
r, "geek" );
cout << result;
return 0;
}
|
Output
I am looking for geek
I am looking for geek
So Regex operations make use of following parameters :
- Target sequence (subject) – The string to be matched.
- Regular Expression (Pattern) – The regular expression for the target sequence.
- Matched Array – The information about matches is stored in a special match_result array.
- Replacement String – These string are used for allowing replacement of the matches.
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!