0

这是我的原始方法:

- (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];
}

这就是我想出的。这个对吗?

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;
    }
}
4

1 回答 1

1

我觉得它看起来不错,尽管我想指出使用 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);
}
于 2012-07-17T23:17:36.877 回答