简体   繁体   中英

Matcher regex not matching pattern

I have created a method which I am hoping to find @gmail.com within a set string, with testing passing in for example stackoverflow@gmail.com the method returns false.

I've searched but I am unsure what i am missing, as I am using .matches() is matches.find() necessary?

public final static boolean isGmail(String s) {

    Pattern pattern = Pattern.compile("(\\W|^)[\\w.+\\-]*@gmail.com(\\W|$)");
    System.out.println(pattern + "            pp  ");
    Matcher m = pattern.matcher(s);
    System.out.println(m + "            pp  ");
    boolean b = m.matches();
    System.out.println(b + "            pp  ");
    return b;
}

}

Regex I am very new to, so that could be the issue I accept.

If you want to find "@gmail.com" within string, you should use find() method to achieve correct behaviour.

The difference between match() and find() is, that match() method attempts to match the entire region of the tested string against pattern, while find() attempts to find next subsequence of the tested string that matches the pattern (see https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html ). Hope it helps.

The regex you need is:

[A-Z0-9._%+-]+@gmail\.com

public final static boolean isGmail(String s) {
    return s.matches("(?i).*?[A-Z0-9._%+-]+@gmail\\.com.*");
}

You don't need to use a regex for this, you can just do

public final static boolean isGmail(String s) {
    return s.indexOf("@gmail.com") > -1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM