NSString中解析URL

    技术2022-05-20  41

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

    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]; NSString *someString = @"This is a sample of a http://abc.com/efg.php?EFAei687e3EsA sentence with a URL within it."; NSString *match = [someString substringWithRange:[expression rangeOfFirstMatchInString:someString options:NSMatchingCompleted range:NSMakeRange(0, [someString length])]]; NSLog(@"%@", match); // Correctly prints 'http://abc.com/efg.php?EFAei687e3EsA'

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

    2.系统的NSDataDetector

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

    3.直接操作NSString

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

     


    最新回复(0)