Validate email java

Here is an example of how to validate an email address in Java:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class EmailValidator {
    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" +
            "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    public static boolean validateEmail(String email) {
        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }
}

This code uses a regular expression to match the email address. The regular expression is as follows:

^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@ [A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$

Here's a breakdown of what each part of the regular expression matches:

The $ matches the end of the string.

You can use this class to validate an email address like this:

String email = "[email protected]";
if (EmailValidator.validateEmail(email)) {
    System.out.println("Email is valid");
} else {
    System.out.println("Email is not valid");
}

Note that this is not foolproof and there are many ways to construct an email address that this regular expression would not match. For example, it would not match email addresses with non-ASCII characters or email addresses with non-standard top-level domains. If you need to validate email addresses in a production environment, you may want to consider using a more robust email validation library.