Note that there are some explanatory texts on larger screens.

plurals
  1. POImprove algorithm for finding URLs in a body of text - obj-c
    text
    copied!<p>I'm trying to come up with an algorithm to find URLs in a body of text. I currently have the following code (this was my sit down and hack it out code, and I know there has to be a better way):</p> <pre><code> statusText.text = @"http://google.com http://www.apple.com www.joshholat.com"; NSMutableArray *urlLocations = [[NSMutableArray alloc] init]; NSRange currentLocation = NSMakeRange(0, statusText.text.length); for (int x = 0; x &lt; statusText.text.length; x++) { currentLocation = [[statusText.text substringFromIndex:(x + currentLocation.location)] rangeOfString:@"http://"]; if (currentLocation.location &gt; statusText.text.length) break; [urlLocations addObject:[NSNumber numberWithInt:(currentLocation.location + x)]]; } currentLocation = NSMakeRange(0, statusText.text.length); for (int x = 0; x &lt; statusText.text.length; x++) { currentLocation = [[statusText.text substringFromIndex:(x + currentLocation.location)] rangeOfString:@"http://www."]; if (currentLocation.location &gt; statusText.text.length) break; [urlLocations addObject:[NSNumber numberWithInt:(currentLocation.location + x)]]; } currentLocation = NSMakeRange(0, statusText.text.length); for (int x = 0; x &lt; statusText.text.length; x++) { currentLocation = [[statusText.text substringFromIndex:(x + currentLocation.location)] rangeOfString:@" www." options:NSLiteralSearch]; if (currentLocation.location &gt; statusText.text.length) break; [urlLocations addObject:[NSNumber numberWithInt:(currentLocation.location + 1 + x)]]; } //Get rid of any duplicate locations NSSet *uniqueElements = [NSSet setWithArray:urlLocations]; [urlLocations release]; NSArray *finalURLLocations = [[NSArray alloc] init]; finalURLLocations = [uniqueElements allObjects]; //Parse out the URLs of each of the locations for (int x = 0; x &lt; [finalURLLocations count]; x++) { NSRange temp = [[statusText.text substringFromIndex:[[finalURLLocations objectAtIndex:x] intValue]] rangeOfString:@" "]; int length = temp.location + [[finalURLLocations objectAtIndex:x] intValue]; if (temp.location &gt; statusText.text.length) length = statusText.text.length; length = length - [[finalURLLocations objectAtIndex:x] intValue]; NSLog(@"URL: %@", [statusText.text substringWithRange:NSMakeRange([[finalURLLocations objectAtIndex:x] intValue], length)]); } </code></pre> <p>I feel like it could be improved via the usage of regular expressions or something. Any help in improving this would be greatly appreciated.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload