software-mariodiana
7/26/2013 - 10:40 PM

Cocoa's regular expressions are a little gnarly to use, and using an NSPredicate instead can make things easier. Here, given a list of (lowe

Cocoa's regular expressions are a little gnarly to use, and using an NSPredicate instead can make things easier. Here, given a list of (lowercase) words, we want to filter an array to return a new array that comprises only words beginning with a particular letter. We specify a regular expression, but we let NSPredicate take care of all the plumbing to instantiate and use one.

// Assume all the words in the list are lowercase

- (NSArray *)filterListOfWords:(NSArray *)words byFirstLetter:(NSString *)aLetter
{
    // Use NSPredicate to filter the words in the list
    NSString *regex = [NSString stringWithFormat:@"^%@.*$", [aLetter lowercaseString]];
    NSPredicate *filter = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    NSArray *list = [words filteredArrayUsingPredicate:filter];
    
    return list;
}