Skip to content

Instantly share code, notes, and snippets.

@justin
Created February 8, 2014 16:49
Show Gist options
  • Save justin/8886529 to your computer and use it in GitHub Desktop.
Save justin/8886529 to your computer and use it in GitHub Desktop.
How I fixed my weird NSRegularExpression issue.
BOOL RSHasMarkdownLinks(NSString *x)
{
NSString *searchText = x;
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\[([^\\[]+)\\]\\(([^\\)]+)\\)" options:0 error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:searchText options:0 range:NSMakeRange(0, [searchText length])];
return (numberOfMatches > 0);
}
- (NSArray *)rs_links {
if (RSStringIsEmpty(self))
return nil;
NSString *searchText = self;
if (RSHasMarkdownLinks(searchText))
{
searchText = RSStringReplaceAll(searchText, @"](", @"] (");
}
NSMutableArray *links = [NSMutableArray array];
/*The regex pattern is from Daring Fireball: <http://daringfireball.net/2010/07/improved_regex_for_matching_urls>
It matches things like www.example.com as well as http://example.com/.*/
@autoreleasepool {
static NSString *pattern = @"(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:(NSRegularExpressionOptions)NSMatchingCompleted error:&error];
if (regex == nil)
return nil;
NSArray *matches = [regex matchesInString:searchText options:0 range:NSMakeRange(0, [searchText length])];
for (NSTextCheckingResult *oneResult in matches) {
NSRange oneRange = [oneResult rangeAtIndex:1];
NSString *oneLink = [self substringWithRange:oneRange];
[links rs_safeAddObject:oneLink];
}
}
return links;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment