aahrens
aahrens

Reputation: 5590

NSPredicate for NSString With Custom Format

I'd like to use NSPredicate 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.

Upvotes: 0

Views: 2070

Answers (2)

Benoît
Benoît

Reputation: 7427

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)'"]

Upvotes: 4

Dave DeLong
Dave DeLong

Reputation: 243156

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)

Upvotes: 2

Related Questions