I am using an email validation pattern I found at How to validate an email and it works fine except it allows a +
in the first part of the email and that isn't allowed in my specs. The original code is
public 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,})$";
protected boolean isInvalidEmail(String email) {
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return !matcher.matches();
}
I thought I could just remove the +
from "^[_A-Za-z0-9-\\\\+]
but I get a Pattern Syntax Exception: Unclosed Character Class
. Can someone tell me why removing the +
uncloses the class? Thanks!
You have to remove the \\\\+
portion.
\\\\
escapes the \\
character. \\+
escapes the +
regex operator. Thus \\\\+
breaks down to \\+
which means match the literal +
character.
Note: The +
regex operator means match one or more of the preceding element.
The reason that it gives you Unclosed Character Class
is because only removing the +
now escapes the closing square bracket so it is considered part of the pattern. Hence, the class does not have a matching closing square bracket. As Jonny Henly mentions the solution is to remove the \\\\+
to align with your spec, but this gives the answer as to why it is unclosed.
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.