2013-05-16 68 views
1

我想驗證YouTube網址http://www.youtube.com/watch?v=UdQfR4nsXvI。採用下面的代碼如何驗證objective-C中的youtube網址?

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

} 

我想也驗證任何YouTube網址格式....

編輯的代碼:


- (IBAction)uplaod_video_Action:(id)sender 
{ 
    NSURL *candidateURL = [NSURL URLWithString:youtube_Url.text]; 

    // WARNING > "test" is an URL according to RFCs, being just a path 
    // so you still should check scheme and all other NSURL attributes you need 

    if (candidateURL && candidateURL.scheme && candidateURL.host) 
    { 
     // candidate is a well-formed url with: 
     // - a scheme (like http://) 
     // - a host (like stackoverflow.com) 
     NSLog(@"hallo"); 
    } 
    else 
    { 
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Please enter the Email" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; 
     [alert show]; 

    } 
+0

參考http://www.raywenderlich.com/30288/nsregularexpression-tutorial-and-cheat-sheet?utm_source = feedburner&utm_medium = feed&utm_campaign = Feed%3A + RayWenderlich +%28Ray + Wenderlich +%7C + iPhone + Developer + and + Gamer%29 –

回答

0

試這

NSString *urlRegEx = @"(^http:\/\/(?:www\.)?youtube.com\/watch\?(?=[^?]*v=\w+)(?:[^\s?]+)?$); 
0

嘗試使用這一

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

NSString *urlRegEx = @"(?<=v(=|/))([-a-zA-Z0-9_]+)|(?<=youtu.be/)([-a-zA-Z0-9_]+)"; 

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

return [urlTest evaluateWithObject:candidate]; 

} 
+0

我得到了未知的轉義序列\。 ..它不工作 – user2389500

+0

@ user2389500看到我編輯的答案..我已經改變了它 –

+0

當我給url中的「http:www」時,它也正在採取 – user2389500