Last active
December 20, 2015 07:19
-
-
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…
This file contains 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
// 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