i am having fallowing email id
闪闪发光@闪闪发光.com
i need to validate this type of email at server side so that user can not enter this type of email..
i have solved similar problem in 开发者_开发百科javascript by using below regex-/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/gi
But. unable to do same thing in java.Please help me guys.
Thanks in advance!!!The Java regular expression pattern (?i)[-a-z0-9+_][-a-z0-9+_.]*@[-a-z0-9][-a-z0-9.]*\\.[a-z]{2,6}
should suffice. Here's what the pattern means:
(?i) # Case insensitive flag
[-a-z0-9+_] # First character
[-a-z0-9+_.]* # Zero or more characters
@ # Literal '@' character
[-a-z0-9] # Match a single character
[-a-z0-9.]* # Match zero or more characters
\. # Literal '.' character
[a-z]{2,6} # Match 2 through 6 alpha characters
The following test code ...
final String ps =
"(?i)[-a-z0-9+_][-a-z0-9+_.]*@[-a-z0-9][-a-z0-9.]*\\.[a-z]{2,6}";
final Pattern p = Pattern.compile(ps);
for (String s : new String[] {"foo@bar.COM", "+foo@bar.COM",
"-foo@bar.COM", "fo_o@bar.COM", "f.oo@bar.COM", "a@b.cdefgh",
"3@4.com", "3@4.5.6-7.8.com", ".foo@bar.com", "a@b.cdefghi",
"闪闪发光@闪闪发光.com"})
{
final Matcher m = p.matcher(s);
if (m.matches()) {
System.out.println("Success: " + s);
} else {
System.out.println("Fail: " + s);
}
}
... will output:
Success: foo@bar.COM
Success: +foo@bar.COM
Success: -foo@bar.COM
Success: fo_o@bar.COM
Success: f.oo@bar.COM
Success: a@b.cdefgh
Success: 3@4.com
Success: 3@4.5.6-7.8.com
Fail: .foo@bar.com
Fail: a@b.cdefghi
Fail: 闪闪发光@闪闪发光.com
By using the Matcher.matches()
method, you don't need to include the ^
start-of-line or $
end-of-line boundary matching constructs since Matcher.matches()
will match on the whole string.
[Update] Sorry for the js code. Try this:
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();
}
}
精彩评论