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,
- The \w matches any character in any case any number of times.
- Then the \.|_ matches if a dot or underscore is present 0 or 1 times.
- Then \w again match n characters.
- Then @ matches the @ in the email.
- 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:[email protected] Your Email-Id is valid
Output 2:
Enter your Email-Id:[email protected]+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,
Leave a Reply