NSPredicates beginsWith
I have an NSArray whose contents are strings with a format similar to: [A-z]{+}-[0-9]{+}
so basically a bunch of repeating alpha characters, a separator, and then 1 or more digits so
I want to filter by values in the array that match up to the separator but I can't seem to explicitly spec开发者_如何学运维ify it in my predicator's format:
NSPredicate *aPredicate = [NSPredicate predicateWithFormat:@"self BEGINSWITH %@", aValue];
NSArray *filtered = [entries filteredArrayUsingPredicate:aPredicate];
How do you constrain the filtering for such a case?
You could use the "MATCHES" operator to do a regular expression search, like so:
NSPredicate * p = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"[a-z]+-.*"];
NSArray * s = [NSArray arrayWithObject:@"abc-123"];
NSLog(@"%@", [s filteredArrayUsingPredicate:p]);
There is a caveat, though. The regular expression is matched across the entire string. So if you want to find all the elements that begin with 3 letters, your expression can't just be "[a-z]{3}". It has to be "[a-z]{3}.*". The first will fail for anything that's not 3 letters, whereas the second will match anything that's at least 3 letters long.
Took me a while to realize this...
You probably want to use the MATCHES operator that lets you use Regular Expressions.
See Predicate Programming Guide:Regular Expressions
精彩评论