需求很简单,是从一段文本中匹配出其中的超连接。基本的作法就是用正则表达式去匹配。可是有这样一个问题。git
网上大部分的识别URL的正则表达式url末尾有空格的状况下能够正确识别。好比这样的状况。github
我是一段中文https://github.com/TinyQ 我仍是一段中文正则表达式
可是若是去掉TinyQ 后面的空格。匹配到的将是 “https://github.com/TinyQ我仍是一段中文” 是连上的。url
最后替换过好多正则才得以解决。这里贴上代码:spa
NSError *error; NSString *regulaStr = @"\\bhttps?://[a-zA-Z0-9\\-.]+(?::(\\d+))?(?:(?:/[a-zA-Z0-9\\-._?,'+\\&%$=~*!():@\\\\]*)+)?"; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr options:NSRegularExpressionCaseInsensitive error:&error]; NSArray *arrayOfAllMatches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])]; for (NSTextCheckingResult *match in arrayOfAllMatches) { NSString* substringForMatch = [string substringWithRange:match.range];
NSLog(@"substringForMatch");
}
这里作个更新。下面这个正则也是能够的。并且应该更好一些。code
好比这种 Explorerwww.chiphell.com/ 。 也是能够识别出 www.chjiphell.com 的blog
((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)ip