26

I have a NSPredicate like this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"entity.name CONTAINS %@", myString];

But that will return anything which contains that string. For example: If my entity.name's where:

text
texttwo
textthree
randomtext

and the myString was text then all of those strings would match. I would like it so that if myString is text it would only return the first object with the name text and if myString was randomtext it would return the fourth object with the name randomtext. I am also looking for it to be case insensitive and that it ignores whitespace

CoreCode
  • 2,227
  • 4
  • 22
  • 24

2 Answers2

65

This should do it:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"entity.name LIKE[c] %@", myString];

LIKE matches strings with ? and * as wildcards. The [c] indicates that the comparison should be case insensitive.

If you don't want ? and * to be treated as wildcards, you can use == instead of LIKE:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"entity.name ==[c] %@", myString];

More info in the NSPredicate Predicate Format String Syntax documentation.

Andrew Madsen
  • 21,309
  • 5
  • 56
  • 97
  • Ahh, sorry I missed that part. I think for whitespace insensitivity, you must use MATCHES and provide a regular expression instead of a simple match string. dasblinkenlight's answer demonstrates this. – Andrew Madsen Jul 22 '12 at 03:36
13

You can use regular expression matcher with your predicate, like this:

NSString *str = @"test";
NSMutableString *arg = [NSMutableString string];
[arg appendString:@"\\s*\\b"];
[arg appendString:str];
[arg appendString:@"\\b\\s*"];
NSPredicate *p = [NSPredicate predicateWithFormat:@"SELF matches[c] %@", arg];
NSArray *a = [NSArray arrayWithObjects:@" test ", @"test", @"Test", @"TEST", nil];
NSArray *b = [a filteredArrayUsingPredicate:p];

The piece of code above constructs a regular expression that matches strings with optional blanks at the beginning and/or at the end, with the target word surrounded by the "word boundary" markers \b. The [c] after matches means "match case-insensitively".

This example uses an array of strings; to make it work in your environment, replace SELF with entity.name.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • It's good, it works, but if you're going to use `matches`, then you may not want to match the spaces explicitly (in case you're going to perform substitution), and for that you can simplify both your `@"\\s*\\b"` and `@"\\b\\s*"` to `@"\\b"` directly: `NSString *arg = [NSString stringWithFormat:@"\\b%@\\b", str];` – Cœur Mar 15 '18 at 09:12