Java判斷郵箱是否合法


public class Test {
    public static void main(String[] args) {

        //電子郵件
         String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
         Pattern regex = Pattern.compile(check);
         Matcher matcher = regex.matcher("dffdfdf@qq.com");
         boolean isMatched = matcher.matches();
         System.out.println(isMatched);
    }

    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        String mail=null;
        System.out.println("請輸入E-Mail:");
        mail=scanner.next();
        Pattern pattern=Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}");//\w表示a-z,A-Z,0-9(\\轉義符)
        Matcher matcher=pattern.matcher(mail);
        boolean b=matcher.matches();
        if (b) {
            System.out.println(mail+"有效的郵箱地址!");
        }else {
            System.out.println(mail+"的格式錯誤!!");
        }
    }



    /**
    *javascript電子郵箱的合法性驗證
    */
    function isEmail(email)
      {
            var srt=/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
              if(srt.test(email))
              {
                  //不合法時
                  return false;
              }
              else
              {
                  //合法時
                return true;
              }
      }
}

public static boolean validateEmail(String email) {
   boolean flag = false;
   int pos = email.indexOf("@");
   if (pos == -1 || pos == 0 || pos == email.length() - 1) {
     return false;
   }
   String[] strings = email.split("@");
   if (strings.length != 2) {// 如果郵箱不是xxx@xxx格式
     return false;
   }
   CharSequence cs = strings[0];
   for (int i = 0; i < cs.length(); i++) {
     char c = cs.charAt(i);
     if (!Character.isLetter(c) && !Character.isDigit(c)) {
       return false;
     }
   }
   pos = strings[1].indexOf(".");// 如果@后面沒有.,則是錯誤的郵箱。
   if (pos == -1 || pos == 0 || pos == email.length() - 1) {
     return false;
   }
   strings = strings[1].split(".");
   for (int j = 0; j < strings.length; j++) {
     cs = strings[j];
     if (cs.length() == 0) {
     return false;
     }
     for (int i = 0; i < cs.length(); i++) {//如果保護不規則的字符,表示錯誤
       char c = cs.charAt(i);
       if (!Character.isLetter(c) && !Character.isDigit(c)) {
       return false;
       }
     }
   }
   return true;
 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM