Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate with a string matching beginning of words

This must be a duplicate. But with so many NSPredicate questions out there, I can't find the right one.

I have a list of Core Data objects that contain a compositeName field. A name like 'Emily Blunt' could be in there. I want to search the list using an NSPredicate that will let me search for "Em" but also for "Bl" and then have this name show up in the fetched results.

This must be super easy, but as you'd guess, I'm not seeing it. My dysfunctional attempt at an NSPredicate with a regular expression looks like this:

[NSPredicate predicateWithFormat:@"compositeName MATCHES[cd] '.*(?<=^|\\s)%@.*'", query];

My thought for this regular expression were:

  • any number of characters before
  • negative lookbehind spaces or beginning
  • the query
  • any number of characters after

But it's not working. I'm not getting any results. How do I fix this?

P.S. If there's an NSPredicate solution without Regular Expressions that would suit my purpose too.

like image 261
epologee Avatar asked Jun 17 '12 12:06

epologee


1 Answers

You need to build the whole regex pattern string outside of the predicate string, then pass it to the predicate.

Also, there is a regex construct \b to match a word boundary, which is what you are after.

So altogether, this snippet should give you a simple solution to your problem:

NSString *searchString = @"Em";
NSString *regexString  = [NSString stringWithFormat:@".*\\b%@.*", searchString];

NSPredicate *pred = [NSPredicate predicateWithFormat:@"self.compositeName matches[cd] %@", regexString];

If the input search text has not been cleaned, you might want to do that before you pass it on to the regex engine.

Another improvement could be to accept unicode characters at the word boundary to allow people to search for 'Ántonio', 'Über' and other similar strings.

The following lines of code will create a regex pattern that will take care of both aspects:

NSString *orgSearchString = @"^";

NSString *escapedSearchString = [NSRegularExpression escapedPatternForString: orgSearchString];

NSString *regexString  = [NSString stringWithFormat:@"(?w:).*\\b%@.*", escapedSearchString];
like image 93
Monolo Avatar answered Sep 17 '22 18:09

Monolo