-
Notifications
You must be signed in to change notification settings - Fork 3
/
NSString+URLsFromString.m
55 lines (41 loc) · 1.86 KB
/
NSString+URLsFromString.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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