Last active
January 3, 2019 16:25
-
-
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 *> *`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSString+URLsFromString.h | |
// | |
@interface NSString (URLsFromString) | |
+ (NSArray <NSURL*> *)URLsFromString:(NSString *)string; | |
- (NSArray <NSURL*> *)URLs; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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