Skip to content

Commit

Permalink
Update NSString+URLsFromString.m
Browse files Browse the repository at this point in the history
  • Loading branch information
midnightchip authored Jan 15, 2019
1 parent 9f2cc63 commit 99742a1
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions NSString+URLsFromString.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
//
// NSString+URLsFromString.m
//
//
// Created by midnightchips on 12/24/18.
//
//

@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

0 comments on commit 99742a1

Please sign in to comment.