The Wayback Machine - https://web.archive.org/web/20240914180320/https://www.geeksforgeeks.org/regex-regular-expression-in-c/
Open In App

std::regex_match, std::regex_replace() | Regex (Regular Expression) In C++

Last Updated : 04 Jul, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Hard
23.88%
60.4K

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




// C++ program to demonstrate working of regex_match()
#include <iostream>
#include <regex>
 
using namespace std;
int main()
{
    string a = "GeeksForGeeks";
 
    // Here b is an object of regex (regular expression)
    regex b("(Geek)(.*)"); // Geek followed by any character
 
    // regex_match function matches string a against regex b
    if ( regex_match(a, b) )
        cout << "String 'a' matches regular expression 'b' \n";
 
    // regex_match function for matching a range in string
    // against regex b
    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




// C++ program to demonstrate working of regex_search()
#include <iostream>
#include <regex>
#include<string.h>
using namespace std;
 
int main()
{
    // Target sequence
    string s = "I am looking for GeeksForGeeks "
               "articles";
 
    // An object of regex for pattern to be searched
    regex r("Geek[a-zA-Z]+");
 
    // flag type for determining the matching behavior
    // here it is for matches on 'string' objects
    smatch m;
 
    // regex_search() for searching the regex pattern
    // 'r' in the string 's'. 'm' is flag for determining
    // matching behavior.
    regex_search(s, m, r);
 
    // for each loop
    for (auto x : m)
        cout << x << " ";
 
    return 0;
}


Output

GeeksForGeeks 

regex_replace() This function is used to replace the pattern matching to the regular expression with a string.

CPP




// C++ program to demonstrate working of regex_replace()
#include <iostream>
#include <string>
#include <regex>
#include <iterator>
using namespace std;
 
int main()
{
    string s = "I am looking for GeeksForGeek \n";
     
    // matches words beginning by "Geek"
    regex r("Geek[a-zA-z]+");
     
    // regex_replace() for replacing the match with 'geek'
    cout << std::regex_replace(s, r, "geek");
     
    string result;
     
    // regex_replace( ) for replacing the match with 'geek'
    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.


Similar Reads

std::fixed, std::scientific, std::hexfloat, std::defaultfloat in C++
Formatting in the standard C++ libraries is done through the use of manipulators, special variables or objects that are placed on the output stream. There are two types of floating point manipulators namely, fixed floating point and scientific floating point. These all are defined in header &lt;iostream&gt;. Use of precision : In the default floati
3 min read
std::oct , std::dec and std::hex in C++
This function is used to set the base to octal, decimal or hexadecimal. It sets the basefield format flag for the str stream to the specified base std::oct : When basefield is set to octal, integer values inserted into the stream are expressed in octal base (i.e., radix 8). For input streams, extracted values are also expected to be expressed in oc
2 min read
std::string::length, std::string::capacity, std::string::size in C++ STL
Prerequisite: String in C++ String class is one of the features provided by the Standard template library to us, So it comes up with great functionality associated with it. With these Functionalities, we can perform many tasks easily. Let's see a few of the functionalities string class provides. Header File &lt;string&gt; String Functionalities The
6 min read
std::stod, std::stof, std::stold in C++
std::stod() : It convert string into double. Syntax: double stod( const std::string&amp; str, std::size_t* pos = 0 ); double stod( const std::wstring&amp; str, std::size_t* pos = 0 ); Return Value: return a value of type double Parameters str : the string to convert pos : address of an integer to store the number of characters processed. This param
3 min read
std::setbase, std::setw , std::setfill in C++
The useful input/output manipulators are std::setbase, std::setw and std::setfill. These are defined in and are quite useful functions. std::base : Set basefield flag; Sets the base-field to one of its possible values: dec, hex or oct according to argument base.Syntax : std::setbase (int base);decimal : if base is 10hexadecimal : if base is 16octal
3 min read
How to validate MAC address using Regular Expression
Given string str, the task is to check whether the given string is a valid MAC address or not by using Regular Expression. A valid MAC address must satisfy the following conditions: It must contain 12 hexadecimal digits.One way to represent them is to form six pairs of the characters separated with a hyphen (-) or colon(:). For example, 01-23-45-67
6 min read
How to validate Indian driving license number using Regular Expression
Given string str, the task is to check whether the given string is a valid Indian driving license number or not by using Regular Expression.The valid Indian driving license number must satisfy the following conditions: It should be 16 characters long (including space or hyphen (-)).The driving license number can be entered in any of the following f
7 min read
How to validate CVV number using Regular Expression
Given string str, the task is to check whether it is a valid CVV (Card Verification Value) number or not by using Regular Expression. The valid CVV (Card Verification Value) number must satisfy the following conditions: It should have 3 or 4 digits.It should have a digit between 0-9.It should not have any alphabet or special characters. Examples: I
5 min read
How to validate SSN (Social Security Number) using Regular Expression
Given string str, the task is to check whether the given string is valid SSN (Social Security Number) or not by using Regular Expression. The valid SSN (Social Security Number) must satisfy the following conditions: It should have 9 digits.It should be divided into 3 parts by hyphen (-).The first part should have 3 digits and should not be 000, 666
6 min read
Validate Corporate Identification Number (CIN) using Regular Expression
Given some Corporate Identification Number, the task is to check if they are valid or not using regular expressions. Rules for the valid CIN are: CIN is a 21 digits alpha-numeric code.It starts with either alphabet letter U or L.Next five characters are reserved for digits (0-9).Next two places are occupied by alphabet letters(A-Z-a-z).Next four pl
6 min read
How to validate PAN Card number using Regular Expression
Given string str of alphanumeric characters, the task is to check whether the string is a valid PAN (Permanent Account Number) Card number or not by using Regular Expression.The valid PAN Card number must satisfy the following conditions: It should be ten characters long.The first five characters should be any upper case alphabets.The next four-cha
6 min read
How to validate time in 24-hour format using Regular Expression
Given a string str, the task is to check whether the string is valid time in 24-hour format or not by using Regular Expression. The valid time in the 24-hour format must satisfy the following conditions. It should start from 0-23 or 00-23.It should be followed by a ':'(colon).It should be followed by two digits from 00 to 59.It should not end with
6 min read
How to validate pin code of India using Regular Expression
Given a string of positive number ranging from 0 to 9, the task is to check whether the number is valid pin code or not by using a Regular Expression. The valid pin code of India must satisfy the following conditions. It can be only six digits.It should not start with zero.First digit of the pin code must be from 1 to 9.Next five digits of the pin
6 min read
How to validate Hexadecimal Color Code using Regular Expression
Given string str, the task is to check whether the string is valid hexadecimal colour code or not by using Regular Expression. The valid hexadecimal color code must satisfy the following conditions. It should start from '#' symbol.It should be followed by the letters from a-f, A-F and/or digits from 0-9.The length of the hexadecimal color code shou
6 min read
How to check string is alphanumeric or not using Regular Expression
Given string str, the task is to check whether the string is alphanumeric or not by using Regular Expression. An alphanumeric string is a string that contains only alphabets from a-z, A-Z and some numbers from 0-9. Examples: Input: str = "GeeksforGeeks123" Output: true Explanation: This string contains all the alphabets from a-z, A-Z, and the numbe
5 min read
How to check Aadhaar number is valid or not using Regular Expression
Given string str, the task is to check whether the given string is a valid Aadhaar number or not by using Regular Expression. The valid Aadhaar number must satisfy the following conditions: It should have 12 digits.It should not start with 0 and 1.It should not contain any alphabet and special characters.It should have white space after every 4 dig
5 min read
How to validate image file extension using Regular Expression
Given string str, the task is to check whether the given string is a valid image file extension or not by using Regular Expression. The valid image file extension must specify the following conditions: It should start with a string of at least one character.It should not have any white space.It should be followed by a dot(.).It should be end with a
5 min read
How to validate GST (Goods and Services Tax) number using Regular Expression
Given string str, the task is to check whether the given string is a valid GST (Goods and Services Tax) number or not using Regular Expression. The valid GST (Goods and Services Tax) number must satisfy the following conditions: It should be 15 characters long.The first 2 characters should be a number.The next 10 characters should be the PAN number
6 min read
How to validate HTML tag using Regular Expression
Given string str, the task is to check whether it is a valid HTML tag or not by using Regular Expression.The valid HTML tag must satisfy the following conditions: It should start with an opening tag (&lt;).It should be followed by a double quotes string or single quotes string.It should not allow one double quotes string, one single quotes string o
6 min read
How to validate IFSC Code using Regular Expression
Given string str, the task is to check whether the given string is a valid IFSC (Indian Financial System) Code or not by using Regular Expression. The valid IFSC (Indian Financial System) Code must satisfy the following conditions: It should be 11 characters long.The first four characters should be upper case alphabets.The fifth character should be
8 min read
How to validate MasterCard number using Regular Expression
Given string str, the task is to check whether the given string is a valid Master Card number or not by using Regular Expression. The valid Master Card number must satisfy the following conditions. It should be 16 digits long.It should start with either two digits numbers may range from 51 to 55 or four digits numbers may range from 2221 to 2720.In
7 min read
How to validate Visa Card number using Regular Expression
Given a string str, the task is to check whether the given string is a valid Visa Card number or not by using Regular Expression. The valid Visa Card number must satisfy the following conditions: It should be 13 or 16 digits long, new cards have 16 digits and old cards have 13 digits.It should start with 4.If the cards have 13 digits the next twelv
6 min read
How to validate GUID (Globally Unique Identifier) using Regular Expression
Given string str, the task is to check whether the given string is a valid GUID (Globally Unique Identifier) or not by using Regular Expression.The valid GUID (Globally Unique Identifier) must specify the following conditions: It should be a 128-bit number.It should be 36 characters (32 hexadecimal characters and 4 hyphens) long.It should be displa
6 min read
Check if an URL is valid or not using Regular Expression
Given a URL as a character string str of size N.The task is to check if the given URL is valid or not.Examples : Input : str = "https://www.geeksforgeeks.org/" Output : Yes Explanation : The above URL is a valid URL.Input : str = "https:// www.geeksforgeeks.org/" Output : No Explanation : Note that there is a space after https://, hence the URL is
4 min read
Validate week days using Regular Expression
Given some Weekdays, the task is to check if they are valid or not using regular expressions. Rules for the valid Weekdays : It should contain specific only words as a string. They are mentioned below:Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday.Mon, Tues, Wed, Thurs, Fri, Sat, Sun. Mon., Tues., Wed., Thurs., Fri., Sat., Sun.
5 min read
Validate localhost API request processed by POSTMAN using Regular Expression
Given some Postman APIs, the task is to check if they are valid or not using regular expressions. Rules for the valid API: It is an alphanumeric String, a combination of alphabets ( 'a' to 'z') and digits (0 to 9).It should always start with HTTP and must contain some special symbols (':', '/')It should not contain any whitespaces. Examples: Input:
6 min read
How to Validate MICR Code using Regular Expression?
MICR stands for Magnetic Ink Character Recognition. This technology provides transaction security, ensuring the correctness of bank cheques. MICR code makes cheque processing faster and safer. MICR Technology reduces cheque-related fraudulent activities. Structure of a Magnetic Ink Character Recognition(MICR) Code: It is a 9-digit code.It should be
6 min read
Validating Indian vehicle number plate using Regular Expression
Given a string str, the task is to validate if this string represents an Indian vehicle number. A Number Plate consists of three parts : Where, UP: First two Characters denote the State Name. Basically, Initial Characters of a State is used i.e. If the vehicle is from Uttar Pradesh then, UP Will denote the State Name. 50:Next Two Numbers indicate D
7 min read
Validating Voter ID Card using Regular Expression
Voter ID card is also known as EPIC (Electors Photo Identity Card). EPIC is an identification proof for Indian citizens over the age of 18.Given some Voter ids, the task is to check if they are valid or not using regular expressions. Rules for the valid VOTER ID: EPIC Number is a unique alphanumeric code. combination of alphabets ( A to Z)and digit
6 min read
Regular Expression to Validate a Bitcoin Address
BITCOIN is a digital currency. During the digital currency transaction, a BTC address is required to verify the legality of a bitcoin wallet a Bitcoin address is a long set of alphanumeric characters that contains numbers and letters. A Bitcoin address indicates the source or destination of a Bitcoin payment. A Bitcoin wallet is a digital wallet th
6 min read