验证java中的电子邮件格式

时间:2014-10-17 11:07:29

标签: java regex email-validation

我需要验证以alphabat开头并以@gmail.com结尾的电子邮件模式。以下是我的代码。

 public static boolean isValidEmail(String email)
 {
    String endPattern = "@gmail.com";

    if(null == email){
        return false;
    }   
    if(email.length()<10){
        return false;
    }   
    if(!email.endsWith(endPattern)){
        return false;
    }
    String[] strArr = email.split(endPattern);  
    String mailId = strArr[0];  
    if(!Character.isLetter((mailId.charAt(0)))){
        return false;
    }   
    return true;
  }

有没有更好的方法来实现这一目标?正则表达式还是更好的代码?

6 个答案:

答案 0 :(得分:3)

使用正则表达式

public static boolean isValidEmail(String email)
{
    if (email != null)
    {
        Pattern p = Pattern.compile("^[A-Za-z].*?@gmail\\.com$");
        Matcher m = p.matcher(email);
        return m.find();
    }
    return false;
}

答案 1 :(得分:1)

使用matches方法检查字符串是否以字母开头,以字符串@gmail.com结尾

System.out.println("foo@gmail.com".matches("[A-Za-z].*?@gmail\\.com"));
System.out.println("8foo@gmail.com".matches("[A-Za-z].*?@gmail\\.com"));

<强>输出:

true
false

答案 2 :(得分:1)

根据谷歌的说法,

电子邮件地址

  • 应以字母或数字开头
  • 只能包含字母(a-z),数字和句点。
  • 应至少为6个字符

正则表达式应该是

Pattern p = Pattern.compile("^[_A-Za-z0-9]+[\\.[A-Za-z0-9]{5,}@gmail\\.com$");

答案 3 :(得分:1)

public class Main {

 public static void main(String[] args) {

  String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\
  @([\\w]+\\.)+[\\w]+[\\w]$";
  String email1 = "user@domain.com";
  Boolean b = email1.matches(EMAIL_REGEX);
  System.out.println("is e-mail: "+email1+" :Valid = " + b);
  String email2 = "user^domain.co.in";
  b = email2.matches(EMAIL_REGEX);
  System.out.println("is e-mail: "+email2
  +" :Valid = " + b);
   }
 }

答案 4 :(得分:1)

package com.mkyong.regex;

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

public class EmailValidator {

    private Pattern pattern;
    private Matcher matcher;

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

    public EmailValidator() {
        pattern = Pattern.compile(EMAIL_PATTERN);
    }

    /**
     * Validate hex with regular expression
     * 
     * @param hex
     *            hex for validation
     * @return true valid hex, false invalid hex
     */
    public boolean validate(final String hex) {

        matcher = pattern.matcher(hex);
        return matcher.matches();

    }
}

答案 5 :(得分:-1)

这是javascript代码

         <script>
  function checkEmail()
      {
     var feedback="";
   var email=document.getElementById("email").value;
  var count=email.length;
  var atpos=email.indexOf('@');
   var atdot=email.lastIndexOf('.');
  var tld=email.substring(atdot);
     if(atpos<1 || atdot<1)
   {
   alert("Email is  Not Valid");
    }
      else if(atpos>atdot)
     {
   alert("Email is  Not Valid");
    }
   else{
   alert("Email is Valid");
       }
      }