2012-07-17 48 views
0

這是我原來的方法:將此Objective-C方法轉換爲適用於Android的Java的正確方法是什麼?

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

回答

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); 
} 
+0

PS我不會進入過於複雜的正則表達式 - 它似乎工作,但你應該嘗試並使用測試電子郵件地址的其他方法 - 過於複雜的正則表達式是一個噩夢閱讀和維護。 – 2012-07-17 23:18:38

相關問題