2011-11-22 37 views
6

我試圖驗證這種方法的URL:URL驗證(Objective-C的)

代碼:

- (BOOL) validateUrl: (NSString *) candidate { 

    NSString *urlRegEx= 
    @"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)"; 

    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx]; 
    return [urlTest evaluateWithObject:candidate]; 

} 

它不起作用。我認爲問題出在正則表達式上。

回答

13

您可以使用+ (id)URLWithString:(NSString *)URLString方法NSURL,如果字符串格式不正確,則返回nil。使用if (URL && URL.scheme && URL.host)檢查URL。

+1

我試了一下!但它仍然行不通!例如「ht://www.yahoo」。這個效果很好!它不會回來! –

+2

根據RFC 2396,這是有效的URI。來自apple文檔用於初始化NSURL對象的字符串。必須是符合RFC 2396的URL。此方法根據RFC 1738和1808解析URLString。使用「if(URL && URL.scheme && URL.host)」來檢查URL。 –

+3

RFC 2396使用^(([^:/?#] +):)?(//([^ /?#] *))?([^?#] *)(\?([^#]) *))?(#(。*))?正則表達式。欲瞭解更多信息,請參閱http://www.ietf.org/rfc/rfc2396.txt –

7

嘗試用這個..

- (BOOL) validateUrl: (NSString *) candidate { 
    NSString *urlRegEx = 
    @"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+"; 
    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx]; 
    return [urlTest evaluateWithObject:candidate]; 
} 

它可以幫助你出來。

+0

它不適用於結尾處帶'/'的網址...: - / –

1
NSString *urlRegEx = @"http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";