【问题标题】:Java RegEx for email domain用于电子邮件域的 Java RegEx
【发布时间】:2018-10-29 17:12:27
【问题描述】:

我尝试将注册表单(Android 应用)中的电子邮件选项限制为仅限我大学的域(即***********@aou.edu.sa***********@arabou.edu.sa)。

到目前为止我得到的代码是这样的:

public void validateEmail(EditText anEmail){

    //String regex declaration for student emails
    String emailPatS = "^[_A-Za-z0-9-+]+(\\.[_A-Za-z0-9-]+)*@" + "[aou.edu.sa]";

    //string regex declaration for tutor emails
    String emailPatT = "^[_A-Za-z0-9-+]+(\\.[_A-Za-z0-9-]+)*@" + "[arabou.edu.sa]";

    //Pattern declaration for student and tutor emails
    Pattern studentPat = Pattern.compile(emailPatS);
    Pattern tutorPat = Pattern.compile(emailPatT);

    //Matcher declaration for student and tutor emails
    Matcher studentMatch = studentPat.matcher(anEmail.getText().toString());
    Matcher tutorMatch = tutorPat.matcher(anEmail.getText().toString());

    //if else for email editText validation
    if(studentMatch.matches()){
        submitForm();
    } else {
        //if it doesn't match, first don't allow the user to click sign up button
        //then compare to see if it's a tutor's email
        signUp.setEnabled(false);
        if(tutorMatch.matches()){ //if it does match a tutor's email then allow the user to click sign up and submit the form
            signUp.setEnabled(true);
            submitForm();
        } else { //if it matches neither student nor tutor emails then disallow user to
            //click sign up and toast an error message
            signUp.setEnabled(false);
            anEmail.setError("Please enter your university email only.");
            if(regEmail.isInEditMode()){
                signUp.setEnabled(true);
            }
        }
    }
}

但每次我尝试运行应用程序时,它都会在注册活动中崩溃,这是由于这段特殊的代码。

有什么更简单的替代方法吗?

【问题讨论】:

  • CRASH 然后添加错误logcat...
  • 我不确定您的 reqex 是否正确String emailPatS = "^[_A-Za-z0-9-+]+(\\.[_A-Za-z0-9-]+)*@" + "[aou.edu.sa]"; 您是否看到任何以数字开头的电子邮件 ID
  • 我刚刚又试了一次。它不再崩溃,但电子邮件正则表达式不符合模式并且不会触发错误。
  • 您可以使用一个正则表达式同时使用^[_A-Za-z0-9-+]+(?:\.[_A-Za-z0-9-]+)*@(?:aou\.edu\.sa|arabou\.edu\.sa)$ 注册学生和导师。见Demo。正如@lexicore 指出的那样,没有完美的电子邮件正则表达式。此正则表达式仅基于您在问题中已有的内容。
  • public void validateEmail(EditText anEmail){ String email = anEmail.getText().toString(); boolean endsWithDomain = email.endsWith("aou.edu.sa"); if(endsWithDomain && Patterns.EMAIL_ADDRESS.matcher(email).matches()) { // 做你想做的 } else { Log.d("App","Email not verify");} }

标签: java android regex string email


【解决方案1】:

尝试以下正则表达式并查看演示 Regex101

^([_A-Za-z0-9-+]+\.?[_A-Za-z0-9-+]+@(aou.edu.sa|arabou.edu.sa))$

问题在于捕获电子邮件的域 - @ 之后的部分。您使用了[] 括号,它定义了一组禁止/允许的字符(取决于^)的用法。如果您只有少量的可能性,您可以简单地在() 括号之间定义它们并用| (or) 字符分隔。

(aou.edu.sa|arabou.edu.sa)

在我上面介绍的正则表达式中,它可以识别只有一个点 . 的电子邮件(据我从您的尝试中了解到)。您可以进行简单的更改以允许更多点。

编辑:不要忘记在 Java 中用双斜线 \\ 转义点字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 2014-05-26
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    相关资源
    最近更新 更多