Suresh Varma
Suresh Varma

Reputation: 9740

NSPredicate for Regular Search

I am using NSPredicate for the performing Search as it does on iPhone when we search for any app.

I have say for example 4 keywords

  1. Deccan
  2. New Delhi
  3. Ahmedabad
  4. Salaam Delhi

I have tried creating a predicate with

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"keyword BEGINSWITH[c] 'd'" It gives me Deccan as output. But the problem is I want each word starting with d So from the above example I need output as Deccan, New Delhi, Salaam Delhi but NOT Ahmedabad

Stucked in this issue from hours. tried contains, matches but my bad luck..

Any help towards right path will really be appreciated..

Upvotes: 8

Views: 1942

Answers (3)

Suresh Varma
Suresh Varma

Reputation: 9740

Thanks guys for your responses Here's what I come up with

NSString *matchString =  [NSString stringWithFormat: @".*\\b%@.*",searchText];
NSString *predicateString = @"keyword MATCHES[c] %@";
NSPredicate *predicate =[NSPredicate predicateWithFormat: predicateString, matchString];

Upvotes: 13

Jody Hagins
Jody Hagins

Reputation: 28349

Consider "like" and "matches." Note, however, that these are relatively expensive operations, and can take considerable time on large data sets.

In this example, I assume what you want is to match if any space-separated word in starts with "d"

This checks to see if keyword either begins with 'd' or has a sequence with a followed by 'd'

[NSPredicate predicateWithFormat:@"(keyword BEGINSWITH[c] 'd') OR (keyword LIKE[c] '* d')"]

This one uses a regular expression, which is very similar (use the regex that best suites your situation:

[NSPredicate predicateWithFormat:@"keyword MATCHES[c] '^d.*|.*\\sd.*'"]

Upvotes: 0

Nikita Pestrov
Nikita Pestrov

Reputation: 5966

There are two way for you

  1. Divide the steing by ' ' and use your NSPredicate *predicate = [NSPredicate predicateWithFormat:@"keyword BEGINSWITH[c] 'd'"]
  2. Or, the better way, to use two predicates :

predicate = [NSPredicate predicateWithFormat:@"keyword BEGINSWITH[c] 'd' OR keyword contains[c] ' d'"]// i mean,'space+d'

So you'll it will satisfy both of possible cases.

Upvotes: 1

Related Questions