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 に答える