Here is my original method:
- (BOOL)validateEmail:(NSString *)address
{
NSString *emailRegEx = @"[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
return [emailTest evaluateWithObject:address];
}
Here's what I've come up with. Is this correct?
private boolean Validate(String email)
{
Pattern pattern = Pattern.compile("[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?");
Matcher matcher = pattern.matcher(email);
if(matcher.matches())
{
return true;
}
else
{
return false;
}
}
It seems to look alright with me, although I would like to point out some differences you should make when using Java.
// use a pattern as a constant instead, using the Java naming conventions (all uppercase and underscores)
private static final String MAIL_PATTERN = "[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?";
// lower case method identifier, does not use field so declare static
private static boolean validate(final String email)
{
// matches already returns a boolean, you can use matches directly on a string (shorthand notation)
return email.matches(MAIL_PATTERN);
}
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.