In this blog, we will create a program for regular expression matching in C++ programming language.
What is Regular expression?
A regular expression or regular expressions or regular expressions as they are commonly called are used to represent a particular pattern of string or text. Regexes are often used to indicate the standard text syntax of a string.
Algorithm for the code
The function that is regex_match() template is used to match the given pattern. This function returns true if the given expression matches a string. Otherwise, the function returns false.
C++ code for the respective program
#include <iostream> #include <string> #include <regex> using namespace std; int main () { if (regex_match ("softwareTesting", regex("(soft)(.*)") )) cout << "string:literal => matched\n"; const char mystr[] = "SoftwareTestingHelp"; string str ("software"); regex str_expr ("(soft)(.*)"); if (regex_match (str,str_expr)) cout << "string:object => matched\n"; if ( regex_match ( str.begin(), str.end(), str_expr ) ) cout << "string:range(begin-end)=> matched\n"; cmatch cm; regex_match (mystr,cm,str_expr); smatch sm; regex_match (str,sm,str_expr); regex_match ( str.cbegin(), str.cend(), sm, str_expr); cout << "String:range, size:" << sm.size() << " matches\n"; regex_match ( mystr, cm, str_expr, regex_constants::match_default ); cout << "the matches are: "; for (unsigned i=0; i<sm.size(); ++i) { cout << "[" << sm[i] << "] "; } cout << endl; return 0; }
Output of the above code
Explanation of the code
In the above program, we first compare the string “softwareTesting” with the regular expression “(“(soft)(.*)” using the regex_match function. Then we also demonstrate the different variations of regex_match by passing it a string object, range, etc.