Skip to content

Instantly share code, notes, and snippets.

@software-mariodiana
Last active December 20, 2015 07:19
Show Gist options
  • Save software-mariodiana/6092727 to your computer and use it in GitHub Desktop.
Save software-mariodiana/6092727 to your computer and use it in GitHub Desktop.
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 plumb…
// 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment