Skip to content

Instantly share code, notes, and snippets.

@Adam0101
Created January 13, 2011 15:55
Show Gist options
  • Save Adam0101/778087 to your computer and use it in GitHub Desktop.
Save Adam0101/778087 to your computer and use it in GitHub Desktop.
Example for blog post at www.remarkablepixels.com on NSRegularExpressions
- (NSString *)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:@"https?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?" options:NSRegularExpressionCaseInsensitive error:&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])];
// 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);
// return the matching string
return substringForFirstMatch;
}
return NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment