Skip to content

Instantly share code, notes, and snippets.

@CreatureSurvive
Last active January 3, 2019 16:25
Show Gist options
  • Save CreatureSurvive/5439c5ff76953c9c6b9ea976e8eae032 to your computer and use it in GitHub Desktop.
Save CreatureSurvive/5439c5ff76953c9c6b9ea976e8eae032 to your computer and use it in GitHub Desktop.
NSString category to get all URLs from a string Returns a NSArray of NSURLs `NSArray <NSURL *> *`
//
// NSString+URLsFromString.h
//
@interface NSString (URLsFromString)
+ (NSArray <NSURL*> *)URLsFromString:(NSString *)string;
- (NSArray <NSURL*> *)URLs;
@end
//
// NSString+URLsFromString.m
//
@implementation NSString (URLsFromString)
+ (NSArray <NSURL*> *)URLsFromString:(NSString *)string {
NSMutableArray<NSURL *> *URLs = [NSMutableArray new];
if (string.length) {
NSString *pattern = @"https?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) {
NSString* substring = [string substringWithRange:match.range];
NSURL *candidateURL = [NSURL URLWithString:substring];
if (candidateURL && candidateURL.scheme && candidateURL.host) {
[URLs addObject:candidateURL];
}
}
}
return URLs;
}
- (NSArray <NSURL*> *)URLs {
NSMutableArray<NSURL *> *URLs = [NSMutableArray new];
if (self.length) {
NSString *pattern = @"https?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
NSArray *matches = [regex matchesInString:self options:0 range:NSMakeRange(0, [self length])];
for (NSTextCheckingResult *match in matches) {
NSString* substring = [self substringWithRange:match.range];
NSURL *candidateURL = [NSURL URLWithString:substring];
if (candidateURL && candidateURL.scheme && candidateURL.host) {
[URLs addObject:candidateURL];
}
}
}
return URLs;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment