strave
strave

Reputation: 1481

NSPredicate and NSRegularExpression

That should be really simple but it doesn't want to work. I want to fetch CoreData using a NSPredicate that uses a NSRegularExpression. I would like to search for myString or myString_10 (10 being any possible number, eg. myString_333).

This is my code:

NSString *regexString = [NSString stringWithFormat:@"%@_[0-9]+", value];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString
                                                                           options:NSRegularExpressionSearch                                  
                                                                             error:&error];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(label = %@) OR (label = %@)", value, regex];

value is a string and label is the entity's key.

If value is "New Project", the NSFetchRequest returns an array with one object, although, I have two labels in my model ("New Project" and "New Project_1") that should be fetched.

What am I doing wrong?

Upvotes: 5

Views: 2386

Answers (1)

Joe
Joe

Reputation: 57169

The regular expression needs to be an NSString or part of the predicate when used. See Regular Expressions in the Predicate Programming Guide. Try using MATCHES instead of = and regexString instead of regex. You can reference ICU Regular Expressions for patterns if you have any issues.

Upvotes: 3

Related Questions