Java如何驗證電子郵件地址格式?

2019-10-16 22:25:39

在Java程式設計中,如何驗證電子郵件地址格式?

以下範例演示如何使用String類的matches()方法來驗證電子郵件地址。

package com.yiibai;

public class ValidateEmailFormat {
    public static void main(String[] args) {
        String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
        String email1 = "[email protected]";
        Boolean b = email1.matches(EMAIL_REGEX);
        System.out.println("is e-mail: " + email1 + " :Valid = " + b);
        String email2 = "admin^domain.co.in";
        b = email2.matches(EMAIL_REGEX);
        System.out.println("is e-mail: " + email2 + " :Valid = " + b);
    }
}

上述程式碼範例將產生以下結果 -

is e-mail: [email protected] :Valid = true
is e-mail: admin^domain.co.in :Valid = false

範例-2

以下是如何驗證電子郵件地址格式的另一個範例。

package com.yiibai;

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

public class ValidateEmailFormat2 {
   public static void main(String args[]) {
      List emails = new ArrayList();
      emails.add("[email protected]");
      emails.add("[email protected]");
      emails.add("maxsu%google-cn.com");
      emails.add("[email protected]");
      emails.add("said#@youtube.co.in");
      emails.add("atosll@domaincom");
      emails.add("kitte#gmail.com");
      emails.add("@tw511.com");

      String regex = "^(.+)@(.+)$";
      Pattern pattern = Pattern.compile(regex);

      for (Object email : emails) {
         Matcher matcher = pattern.matcher((CharSequence) email);
         System.out.println(email + " : " + matcher.matches());
      } 
   }
}

上述程式碼範例將產生以下結果 -

[email protected] : true
[email protected] : true
maxsu%google-cn.com : false
[email protected] : true
said#@youtube.co.in : true
atosll@domaincom : true
kitte#gmail.com : false
@tw511.com : false