开发者

NSPredicate for NSString With Custom Format

I'd like to use N开发者_C百科SPredicate to match NSString but I'm having trouble getting started. My goal is to match certain NSStrings that contain the formats of.

  1. be---
  2. be-tt
  3. -----g

If anyone has simple examples that would be greatly appreciated.


You can create a NSPredicate with +predicateWithBlock: with your own comparaison code.

OR using regex (maybe the best solution):

[NSPredicate predicateWithFormat:@"SELF MATCHES '(be...)|(be.tt)|(.....g)'"]


A simple way to do this would be to use the LIKE operator. With this string operator, you can use the special character * and ?. * means "0 or more characters", and ? means "exactly one character". So you could do:

NSPredicate * p = [NSPredicate predicateWithFormat:@"SELF LIKE %@ OR SELF LIKE %@ OR SELF LIKE %@", @"be???", @"be?tt", @"?????g"];
NSLog(@"%d", [p evaluateWithObject:@"beast"]); //logs "1"

(@benoît makes a good observation in his answer that this can also be accomplished with a regular expression [the MATCHES operator], which can cut down on the length of the predicate format string)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜