1
zj
2025-09-16 bb6fe349b56f454f9ec6f01c32f652ecd416f151
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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) ? "有效" : "无效"));
        }
    }
 
}