Cocoa in the Shell

First step with NSRegularExpression

Regular expressions (regex) are often used because they are very practical, but there wasn’t a native Cocoa API to simplify their usage, so programmers often used externals libraries like RegexKitLite.
Perhaps some of you read that applications that used this library would not longer be accepted on the App Store for some reasons, but yet I did not have any problems with it, but who knows what Apple may decide.

With the iOS 4 release, Apple introduced a new class called NSRegularExpression which was exactly what programmers needed, I’ll show you in this post a very simple usage of it.

So let’s get started, suppose I have some html text with img tags in it.
This text is interpreted in an UIWebView, so each time I need to display it, the images have to be downloaded from the net.
Well it’s a bit stupid, so the idea is to download the images once and store them locally for a later reuse. To do this we need to get the URLs of these images and replace them with a local one once the images are downloaded and saved.

Note : This post isn’t about regex syntax, so I’ll not detail it, there are plenty of tutorials on the net which explain this.

NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:@"(?<=img src=").*?(?=")" options:NSRegularExpressionCaseInsensitive error:nil];
// content var is an NSMutableString with my html text
NSArray* imgBalises = [regex matchesInString:content options:0 range:NSMakeRange(0, [content length])];
[regex release];

This simple 3 lines return me a NSArray of NSTextCheckingResult objects of all the occurrences found.
This new class introduced in iOS 4 contains plenty of properties, the one which interests us is range which as its name suggests contains the range of the string found in our text.

NSString* contentCopy = [content copy];
for (NSTextCheckingResult* b in imgBalises) // Loop through the URL list
    NSString* url = [contentCopy substringWithRange:b.range];

    // So stuff to download the image
    // And save it

    [content replaceOccurrencesOfString:url withString:@"LOCAL_PATH" options:NSLiteralSearch range:NSMakeRange(0, [content length])];


So we have simply replaced the strings we wanted with a few lines of code.