用于电子邮件验证的正则表达式的java代码

时间:2014-07-30 07:18:23

标签: java regex

我尝试在java中模拟没有正则表达式的电子邮件验证并编写此代码。我需要帮助来提高此代码的效率(或者让我更好地解决这个问题)

正则表达式:^[(a-zA-Z-0-9-\\_\\+\\.)]+@[(a-z-A-z)]+\\.[(a-zA-z)]{2,3}$

public static boolean isValidEmailAddress(String email) {

    boolean flag1 = false;
    boolean flag2=false;
    boolean flag3=false;
    int j=0;
    char[] emailChars = email.toCharArray();
    for (int i = 0; i < emailChars.length;) {
        char c = emailChars[i];
        if (Character.isLetterOrDigit(c)) {
                i++;
            if(flag1==true&&flag2==true){
                j++;
            }
        } else if (c == '@' && flag1==false&&flag2==false && flag3==false) {
            i++;
            flag1=true;
        } else if(c=='.' && flag1==true && flag2==false&&flag3==false){
            i++;
            flag2 = true;
        }
        if(j==2 || j==3){
            flag3=true;
        }
    }
    return flag1&&flag2&&flag3;

}

2 个答案:

答案 0 :(得分:11)

真实世界的电子邮件验证不是那么原始的任务,它已经解决了很多次。我建议你不要重新发明轮子,而是使用Apache Commons EmailValidator

答案 1 :(得分:2)

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();

    }
}