My app receives numerous text strings which may or may not contain a URL anywhere within the string. What would be the best method to extract a URL from within a string? Thank you.
A:
Regexp is always nice: ^(ht|f)tp:\/\/(w{3}\.)?([\w-]\.*)*([a-zA-Z]{2,4})(\?[\w]+=[\w]+((&[\w]+=[\w]+)*)?)?$/gm
sonstabo
2010-03-14 20:29:53
Don't forget mail URLS - mailto:
Brian Agnew
2010-03-14 20:36:14
or https urls...
Dave DeLong
2010-03-15 03:18:02
+3
A:
The BSD-licensed AutoHyperlinks framework provides classes to scan text for URLs and either return them to you or mark them up as links in an attributed string.
I don't think it builds out of the box for the iPhone, but you could always add preprocessor directives to cut out any AppKit-dependent code. The scan-and-return interface should just work, once you get it to build. (Make sure to run the tests.)
Mike Abdullah wrote a patch for iPhone support. You might try that.
Peter Hosey
2010-03-14 20:39:30
Thanks, I tried this but judging by the number of errors and warnings generated, it will require a significant amount work to get this working on the iPhone -
Run Loop
2010-03-14 21:24:27
JK: That can be misleading. A single line of code can produce a lot of errors if it's sufficiently uncompilable, but it's still only one line of code. I think the AppKit-dependent parts of AutoHyperlinks are isolated enough that you could conditionalize them out fairly easily.
Peter Hosey
2010-03-14 21:32:36
+7
A:
If you are working on a Mac application, Mac OS X 10.6 offers a new API to let you detect URLs with the spell checker. You may do it this way.
NSString *s = @"http://example.com"
NSInteger wordCount = 0;
NSOrthography *orthography = nil;
NSArray *checkResults = [[NSSpellChecker sharedSpellChecker] checkString:s range:NSMakeRange(0, [s length]) types:NSTextCheckingTypeLink options:nil inSpellDocumentWithTag:0 orthography:&orthography wordCount:&wordCount];
for (NSTextCheckingResult *result in checkResults) {
NSRange range = result.range;
NSURL *URL = result.URL;
}
zonble
2010-03-15 03:16:18