title: Using NSRegularExpression to extract URLs on the iPhone
body: <p>I'm using the following code on my iPhone app, taken from <a href="http://remarkablepixels.com/blog/2011/1/13/regular-expressions-on-ios-nsregularexpression.html?lastPage=true#comment17182355" rel="nofollow noreferrer">here</a> to extract all URLs from striped .html code.</p>
  
  <p>I'm only being able to extract the first URL, but I need an array containing <strong>all</strong> URLs. My NSArray isn't returning NSStrings for each URL, but the objects descriptions only.</p>
  
  <p>How do I make my <code>arrayOfAllMatches</code> return all URLs, as NSStrings?</p>
  
  <pre><code>-(NSArray *)stripOutHttp:(NSString *)httpLine {
  
  // Setup an NSError object to catch any failures
  NSError *error = NULL;  
  
  // create the NSRegularExpression object and initialize it with a pattern
  // the pattern will match any http or https url, with option case insensitive
  
  NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"http?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?" options:NSRegularExpressionCaseInsensitive error:&amp;error];
  
  // create an NSRange object using our regex object for the first match in the string httpline
  NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:httpLine options:0 range:NSMakeRange(0, [httpLine length])];
  
  NSArray *arrayOfAllMatches = [regex matchesInString:httpLine options:0 range:NSMakeRange(0, [httpLine length])];
  
  // check that our NSRange object is not equal to range of NSNotFound
  if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {
      // Since we know that we found a match, get the substring from the parent string by using our NSRange object
  
      NSString *substringForFirstMatch = [httpLine substringWithRange:rangeOfFirstMatch];
  
      NSLog(@"Extracted URL: %@",substringForFirstMatch);
      NSLog(@"All Extracted URLs: %@",arrayOfAllMatches);
  
      // return all matching url strings
      return arrayOfAllMatches;
  }
  
  return NULL;
  </code></pre>
  
  <p>}</p>
  
  <p>Here is my NSLog output:</p>
  
  <pre><code>Extracted URL: http://example.com/myplayer    
  All Extracted URLs: (
      "&lt;NSExtendedRegularExpressionCheckingResult: 0x106ddb0&gt;{728, 53}{&lt;NSRegularExpression: 0x106bc30&gt; http?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)? 0x1}",
      "&lt;NSExtendedRegularExpressionCheckingResult: 0x106ddf0&gt;{956, 66}{&lt;NSRegularExpression: 0x106bc30&gt; http?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)? 0x1}",
      "&lt;NSExtendedRegularExpressionCheckingResult: 0x106de30&gt;{1046, 63}{&lt;NSRegularExpression: 0x106bc30&gt; http?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)? 0x1}",
      "&lt;NSExtendedRegularExpressionCheckingResult: 0x106de70&gt;{1129, 67}{&lt;NSRegularExpression: 0x106bc30&gt; http?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)? 0x1}"
  )
  </code></pre>