Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..

like image 925
Suresh Varma Avatar asked Apr 23 '12 09:04

Suresh Varma


2 Answers

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];
like image 153
Suresh Varma Avatar answered Nov 04 '22 17:11

Suresh Varma


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.

like image 1
Nikita Pestrov Avatar answered Nov 04 '22 17:11

Nikita Pestrov