Java Regular Expression to validate email address

A regular expression, specified as a string Pattern, be compiled into an instance of this class to search, edit or manipulate text and data. Today we guide how Java regular expression to validate the email address. we created a particular expression ^\\S+@\\S+$, then use it to match the email address:

Way 1: validate email using Java Regular Expression
import java.util.regex.*;
public class JavaRegular{
  public static void main (String [] args) {
    Pattern pattern = Pattern.compile("^\\S+@\\S+$");
    String email = ""
    Matcher matcher = pattern .matcher(email);
    if (matcher .matches()) {
              System.out.println (email  + " is a valid email address");
     } else {
              System.out.println (email  + " is not a valid email address");

Way 2: validate email using Java Regular Expression.
In this way, we use a different regular expression ^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$ to match an email address.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidateEmailAddress{
  public static void main(String args[]){
    String  expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
    CharSequence email = "";
    Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(email );
      System.out.println(email + " is a valid email address.");
      System.out.println(email + " is an invalid email address.");

Rate article
Add a comment

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