Program to validate Email-Id using regex in C++

In this tutorial, we will be learning how to validate email id using C++.

Regular expression can be used to search for a specific pattern in a string. In C++  we need to include <regex> header in the code.

C++ program to validate Email-Id using regular expression

Firstly, we need to write a regular expression to check the email-id is valid or not.

The regular expression is:

"(\\w+)(\\.|_)?(\\w*)@(\\w+)(\\.(\\w+))+"

Here,

  1. The \w matches any character in any case any number of times.
  2. Then the \.|_ matches if a dot or underscore is present 0 or 1 times.
  3. Then \w again match n characters.
  4. Then @ matches the @ in the email.
  5. Then we again check for n characters and a ‘.’ and a word after it, which must be present at least one or more times.

Program:

#include<iostream>
#include<regex>
#include<stdio.h>
using namespace std;

bool Email_check(string email)
{
 		const regex pattern("(\\w+)(\\.|_)?(\\w*)@(\\w+)(\\.(\\w+))+");
    return regex_match(email,pattern);
}
int main()
{
    string str;
    cout<<"Enter your Email-Id:"<<endl;
    cin>>str;
    if(Email_check(str))
        cout<<"Your Email-Id is valid"<<endl;
    else
        cout<<"Your Email-Id is invalid"<<endl;
    return 0;
}
//BY DEVIPRASAD D MAHALE

Ouput 1:

Enter your Email-Id:code_speedy@codes.com
Your Email-Id is valid

Output 2:

Enter your Email-Id:code_speedy@codes+com
Your Email-Id is invalid

Hope, you have understood the concept and program to validate email-id using regex in C++. Feel free to comment.

Also read,

Difference between delete and free() in C++ with an example

Program to calculate percentile of an array in C++

Leave a Reply

Your email address will not be published. Required fields are marked *