insanj
10/28/2015 - 2:18 AM

Replacing hyperlinks, /u/, and /r/ with direct Markdown links

Replacing hyperlinks, /u/, and /r/ with direct Markdown links

NSString *decodedString = [markdown stringByDecodingHTMLEntities]; // prevents crashes (such as with > embedded within []())
NSMutableString *decodedStringWithReplacedURLs = [NSMutableString stringWithString:decodedString];

NSRegularExpression *regexForURLs = [NSRegularExpression regularExpressionWithPattern:@"[-a-zA-Z0-9:_\\+.~#?&//=]{2,256}\\.[^@\\ ][a-z]{2,12}\b(\\/[-a-zA-Z0-9:%_\\+.~#?&//=]*)?" options:NSRegularExpressionCaseInsensitive error:nil];
[regexForURLs enumerateMatchesInString:decodedString options:0 range:NSMakeRange(0, decodedString.length) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
	NSString *matchedURLString = [decodedString substringWithRange:result.range];
	BOOL shouldReplaceMatchesURL = YES;
	if (result.range.location > 0 && result.range.location < decodedString.length+1) { // check if "[" and "]" exist already
		NSString *beginningChar = [decodedString substringWithRange:NSMakeRange(result.range.location-1, 1)];
		NSString *endingChar = [decodedString substringWithRange:NSMakeRange(result.range.location+result.range.length, 1)];
		
		if ([beginningChar isEqualToString:@"["] || [endingChar isEqualToString:@"]"]) {
			shouldReplaceMatchesURL = NO;
		}
	}
	
	if (shouldReplaceMatchesURL) {
		[decodedStringWithReplacedURLs replaceOccurrencesOfString:matchedURLString withString:[NSString stringWithFormat:@"[%@](%@)", matchedURLString, matchedURLString] options:0 range:NSMakeRange(0, decodedStringWithReplacedURLs.length)];
	}
}];

NSMutableString *decodedStringWithReplacedURLsAndDeeplinks = [NSMutableString stringWithString:decodedStringWithReplacedURLs];

NSRegularExpression *regexForUsers = [NSRegularExpression regularExpressionWithPattern:@"(^|\\s)\\/(r|u)\\/\\S+($|\\s)" options:NSRegularExpressionCaseInsensitive error:nil];
[regexForUsers enumerateMatchesInString:decodedStringWithReplacedURLs options:0 range:NSMakeRange(0, decodedString.length) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
	NSString *matchedUserOrRedditString = [[decodedStringWithReplacedURLs substringWithRange:result.range] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	[decodedStringWithReplacedURLsAndDeeplinks replaceOccurrencesOfString:matchedUserOrRedditString withString:[NSString stringWithFormat:@"[%@](https://reddit.com%@)", matchedUserOrRedditString, matchedUserOrRedditString] options:0 range:NSMakeRange(0, decodedStringWithReplacedURLs.length)];
}];