NSString中解析URL

来源:互联网 发布:js只允许输入数字 编辑:程序博客网 时间:2024/05/28 11:29

总结几种方法达到这种目的。

1.正则表达式法。

  1. NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"(?i)//b((?:[a-z][//w-]+:(?:/{1,3}|[a-z0-9%])|www//d{0,3}[.]|[a-z0-9.//-]+[.][a-z]{2,4}/)(?:[^//s()<>]+|//(([^//s()<>]+|(//([^//s()<>]+//)))*//))+(?://(([^//s()<>]+|(//([^//s()<>]+//)))*//)|[^//s`!()//[//]{};:'/".,<>?«»“”‘’]))" options:NSRegularExpressionCaseInsensitive error:NULL];  
  2. NSString *someString = @"This is a sample of a http://abc.com/efg.php?EFAei687e3EsA sentence with a URL within it.";  
  3. NSString *match = [someString substringWithRange:[expression rangeOfFirstMatchInString:someString options:NSMatchingCompleted range:NSMakeRange(0, [someString length])]];  
  4. NSLog(@"%@", match); // Correctly prints 'http://abc.com/efg.php?EFAei687e3EsA'  

至于这个正则表达式,是从网上找的,请看这儿。

2.系统的NSDataDetector

  1. NSString *string = @"This is a sample of a http://abc.com/efg.php?EFAei687e3EsA sentence with a URL within it.";  
  2. NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];  
  3. NSArray *matches = [linkDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])];  
  4. for (NSTextCheckingResult *match in matches) {  
  5.   if ([match resultType] == NSTextCheckingTypeLink) {  
  6.     NSURL *url = [match URL];  
  7.     NSLog(@"found URL: %@", url);  
  8.   }  
  9. }  

3.直接操作NSString

  1. NSURL *url;  
  2.     NSMutableArray *listItems = [[someString componentsSeparatedByString:@" "] mutableCopy];  
  3. for(int i=0;i<[listItems count];i++)  
  4. {  
  5.     NSString *str=[listItems objectAtIndex:i];  
  6.       if ([str rangeOfString:@"http://"].location == NSNotFound)  
  7.           NSLog(@"Not url");  
  8.       else   
  9.         url=[NSURL URLWithString:str];    
  10. }  

 


原创粉丝点击