Regular Expressions in Objective-C

Our first program demonstrates common regular expression tasks in Objective-C. Here’s the full source code:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // This tests whether a pattern matches a string.
        NSError *error = nil;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"p([a-z]+)ch" options:0 error:&error];
        NSString *testString = @"peach";
        NSRange range = NSMakeRange(0, [testString length]);
        BOOL match = [regex numberOfMatchesInString:testString options:0 range:range] > 0;
        NSLog(@"%d", match);

        // Many methods are available on these objects. Here's a match test like we saw earlier.
        NSLog(@"%d", [regex numberOfMatchesInString:@"peach" options:0 range:NSMakeRange(0, 5)] > 0);

        // This finds the match for the regexp.
        NSTextCheckingResult *result = [regex firstMatchInString:@"peach punch" options:0 range:NSMakeRange(0, 11)];
        NSLog(@"%@", [testString substringWithRange:result.range]);

        // This also finds the first match but returns the start and end indexes for the match instead of the matching text.
        NSLog(@"idx: %@", NSStringFromRange(result.range));

        // The Submatch variants include information about both the whole-pattern matches and the submatches within those matches.
        NSLog(@"%@", [regex matchesInString:@"peach punch" options:0 range:NSMakeRange(0, 11)]);

        // The All variants of these functions apply to all matches in the input, not just the first.
        NSArray *allMatches = [regex matchesInString:@"peach punch pinch" options:0 range:NSMakeRange(0, 17)];
        NSMutableArray *allMatchStrings = [NSMutableArray array];
        for (NSTextCheckingResult *match in allMatches) {
            [allMatchStrings addObject:[testString substringWithRange:match.range]];
        }
        NSLog(@"%@", allMatchStrings);

        // Providing a non-negative integer as the limit will limit the number of matches.
        allMatches = [regex matchesInString:@"peach punch pinch" options:0 range:NSMakeRange(0, 17)];
        allMatchStrings = [NSMutableArray array];
        for (int i = 0; i < 2 && i < allMatches.count; i++) {
            NSTextCheckingResult *match = allMatches[i];
            [allMatchStrings addObject:[testString substringWithRange:match.range]];
        }
        NSLog(@"%@", allMatchStrings);

        // The regexp package can also be used to replace subsets of strings with other values.
        NSString *replaced = [regex stringByReplacingMatchesInString:@"a peach" options:0 range:NSMakeRange(0, 7) withTemplate:@"<fruit>"];
        NSLog(@"%@", replaced);

        // The Block variant allows you to transform matched text with a given block.
        replaced = [regex stringByReplacingMatchesInString:@"a peach" options:0 range:NSMakeRange(0, 7) withBlock:^NSString *(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
            return [[testString substringWithRange:result.range] uppercaseString];
        }];
        NSLog(@"%@", replaced);
    }
    return 0;
}

To run the program, compile and execute it:

$ clang -framework Foundation main.m -o regex_example
$ ./regex_example
1
1
peach
idx: {0, 5}
(
    "<NSRegularExpression: 0x100504350> p([a-z]+)ch 0x0"
)
(
    peach,
    punch,
    pinch
)
(
    peach,
    punch
)
a <fruit>
a PEACH

This example demonstrates various regular expression operations in Objective-C using the NSRegularExpression class. It covers pattern matching, finding matches, replacing text, and more. The NSRegularExpression class provides a powerful set of tools for working with regular expressions in Objective-C.

For a complete reference on Objective-C regular expressions, check the NSRegularExpression class documentation in Apple’s developer resources.