Using NSRegularExpression to extract URLs on the iPhone

后端 未结 5 624
耶瑟儿~
耶瑟儿~ 2020-11-30 09:16

I\'m using the following code on my iPhone app, taken from here to extract all URLs from striped .html code.

I\'m only being able to extract the first URL, but I nee

5条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 09:54

    to get all links from a given string

    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 = @"www.facebook.com/link/index.php This is a sample www.google.com of a http://abc.com/efg.php?EFAei687e3EsA sentence with a URL within it.";
    
    NSArray *matches = [expression matchesInString:someString options:NSMatchingCompleted range:NSMakeRange(0, someString.length)];
    for (NSTextCheckingResult *result in matches) {
            NSString *url = [someString substringWithRange:result.range];
            NSLog(@"found url:%@", url);
    }
    

提交回复
热议问题