Languages
[Edit]
EN

Java - validate email with regex

0 points
Created by:
jonrsharpe
406

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

The important thing is that there is no single way to write expressions that validate an email. Some solutions are more precise in validation, 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

Merger articles

  1.  Java - validate email with regex
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