正则表达式没有正确匹配限制值

时间:2016-09-23 06:49:07

标签: java regex

我创建了一个正则表达式来检查电子邮件地址是否包含管理员,固件,服务&修理。如果我在电子邮件地址中添加'''而不是'admin',那么它也会返回true,这根据要求不正确。

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

static String email = "xxxx@admin.com";
static String email1 = "xxxx@ad.com";
static String email2 = "test@irm.jdsu.com";
public static boolean validate(final String hex) {
        pattern = Pattern.compile(EMAIL_PATTERN_New);
        matcher = pattern.matcher(hex);
        return matcher.matches();   
    }
System.out.println(validate(email));     //true
System.out.println(validate(email1));     //true  but it should be false
System.out.println(validate(email2));    //true  but it should be false

与其他电子邮件地址固件,服务,修复相同。

1 个答案:

答案 0 :(得分:1)

您需要将[admin|firmware|repair|service]+替换为(admin|firmware|repair|service)

请参阅this regex demo

[admin|firmware|repair|service]+是一个匹配单独字符的字符类,ad等一次或多次(由于+)。因此,它将匹配adaddfir

(admin|firmware|repair|service)序列分组构造,匹配adminfirmware等。

请注意,您可以通过将[_a-zA-Z0-9]替换为\w来缩短Java中的正则表达式:

private static final String EMAIL_PATTERN_New = "^[\\w+-]+(?:\\.[\\w-]+)*@(?:admin|firmware|repair|service)(?:\\.[A-Za-z0-9]+)*\\.[A-Za-z]{2,}$";

您甚至可以删除^$,因为您正在使用matches()方法使用正则表达式。

Java demo from IDEONE

import java.util.*;
import java.util.regex.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    private static final String EMAIL_PATTERN_New =
            "^[\\w+-]+(?:\\.[\\w-]+)*@(?:admin|firmware|repair|service)(?:\\.[A-Za-z0-9]+)*\\.[A-Za-z]{2,}$";

    public static void main (String[] args) throws java.lang.Exception
    {
        String email = "xxxx@admin.com";
        String email1 = "xxxx@ad.com";
        String email2 = "test@irm.jdsu.com";

        System.out.println(email.matches(EMAIL_PATTERN_New));     // true
        System.out.println(email1.matches(EMAIL_PATTERN_New));    // false
        System.out.println(email2.matches(EMAIL_PATTERN_New));    // false
    }
}