Languages
[Edit]
EN

Java - validate email with regex

0 points
Created by:
Dirask Admin - Marwin
1430

In this article, we would like to show how to validate e-mail addresses in Java using regular expressions.

The important thing is: there is no one way how to write expressions that validates e-mail. Some solutions are more precise in checking correctness, others less.

Internet is filled with different solutions, so the main goal of the article is to gather all of them in one place.

Quick solution:

import java.util.regex.Pattern;

public class StringExample {

    public static void main(String[] args) {
        String correctEmailToCheck = "john@gmail.com";
        String wrongEmailToCheck = "1124Sample@ text...";

        String regex = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}$";
        Pattern compiledPattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);

        System.out.println( compiledPattern.matcher( correctEmailToCheck ).matches() ); // true
        System.out.println( compiledPattern.matcher( wrongEmailToCheck ).matches() );   // false
    }
}

AngualrJS expression example

Google in AngualrJS suggested its own expression that checks e-mail.

Note: full source code is located here.

Regular expression:

^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$

Working example:

import java.util.regex.Pattern;

public class StringExample {

    public static void main(String[] args) {
        String correctEmailToCheck = "john@gmail.com";
        String wrongEmailToCheck = "1124Sample@ text...";

        String regex = 	"^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$";
        Pattern compiledPattern = Pattern.compile( regex );

        System.out.println( compiledPattern.matcher( correctEmailToCheck ).matches() ); // true
        System.out.println( compiledPattern.matcher( wrongEmailToCheck ).matches() );   // false
    }
}

 Output: 

true
false
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join