package com.nq.utils.email;
|
|
import java.util.regex.Matcher;
|
import java.util.regex.Pattern;
|
|
/**
|
* @program: dabaogp
|
* @description:
|
* @create: 2025-09-16 12:00
|
**/
|
public class EmailValidator {
|
|
|
// 邮箱正则表达式
|
private static final String EMAIL_REGEX =
|
"^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@" +
|
"(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
|
|
// 编译正则表达式模式
|
private static final Pattern pattern = Pattern.compile(EMAIL_REGEX);
|
|
/**
|
* 验证邮箱格式是否有效
|
* @param email 待验证的邮箱地址
|
* @return 如果邮箱格式有效返回true,否则返回false
|
*/
|
public static boolean isValidEmail(String email) {
|
if (email == null) {
|
return false;
|
}
|
|
Matcher matcher = pattern.matcher(email);
|
return matcher.matches();
|
}
|
|
// 测试方法
|
public static void main(String[] args) {
|
// 测试用例
|
String[] testEmails = {
|
"test@example.com",
|
"user.name@example.com",
|
"user.name+tag@example.com",
|
"user@sub.example.co.uk",
|
"invalid-email",
|
"missing@domain",
|
"@missingusername.com",
|
"user@.com"
|
};
|
|
for (String email : testEmails) {
|
System.out.println(email + " : " + (isValidEmail(email) ? "有效" : "无效"));
|
}
|
}
|
|
}
|