简体   繁体   中英

Java regular expression to validate email address that end with .services

The regular expression to validate email address using java.util.regex.Matcher is failing. It throws invalid email address or false.

How would i modify the pattern to allow email address that ends with .services

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

String emailAddress = myemail@something.services;

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

Matcher matcher = ADDR_PATTERN.matcher(emailAddress);



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

String emailAddress = myemail@something.services;

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

Matcher matcher = ADDR_PATTERN.matcher(emailAddress);

Rather than using regex, you should use the "built-in" javax.mail.internet.InternetAddress format validator. Regex becomes more complex as you add additional rules, whereas a basic validation and then a strict validation for the suffix is human-readable.

public static boolean isValidEmailAddress(String email) {
    try {
        InternetAddress emailAddr = new InternetAddress(email);
        emailAddr.validate(); //validates email format

        return true;
    } catch (AddressException ex) {
        return false;
    }
}

^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.services$

Pattern pattern = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.services$", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher("myemail@something.services");
    System.out.println("result: "+matcher.find());

base on Java regex email

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM