https://www.softwaretestinghelp.com/regex-in-cpp/
Function Templates Used In C++ Regex
Let’s now discuss some of the important function templates while programming regex in C++.
regex_match()
This function template is used to match the given pattern. This function returns true if the given expression matches the string. Otherwise, the function returns false.
Following is a C++ programming example that demonstrates the regex_match function.
#include
#include
#include
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
In the above program, first, we match the string “softwareTesting” against the regular expression “(“(soft)(.*)” using the regex_match function. Subsequently, we also demonstrate different variations of regex_match by passing it a string object, range, etc.
egex_search()
The function regex_search() is used to search for a pattern in the string that matches the regular expression.
Consider the following C++ program that shows the usage of regex_search().
#include
#include
#include
using namespace std;
int main()
{
//string to be searched
string mystr = "She sells_sea shells in the sea shore";
// regex expression for pattern to be searched
regex regexp("s[a-z_]+");
// flag type for determining the matching behavior (in this case on string objects)
smatch m;
// regex_search that searches pattern regexp in the string mystr
regex_search(mystr, m, regexp);
cout<<"String that matches the pattern:"<
We specify a string and then a regular expression using the regex object. This string and regex are passed to the regex_search function along with the smatch flag type. The function searches for the first occurrence of pattern in the input string and returns the matched string.
regex_replace()
The function regex_replace() is used to replace the pattern matching to a regular expression with a string.
#include
#include
#include
#include
using namespace std;
int main()
{
string mystr = "This is software testing Help portal \n";
cout<<"Input string: "<
Here, we have an input string. We provide a regular expression to match a string starting with ‘p’. Then we replace the matched word with the word ‘website’. Next, we replace the ‘website’ word back to the portal.