Created
January 13, 2011 15:55
-
-
Save Adam0101/778087 to your computer and use it in GitHub Desktop.
Example for blog post at www.remarkablepixels.com on NSRegularExpressions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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