NSPredicate for regular searches

I use NSPredicate to do a search like on the iPhone when we search for any application.

I say, for example, 4 keywords

  • Dean
  • New Delhi
  • Ahmedabad
  • Salama Delhi

I tried to create a predicate with

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"keyword BEGINSWITH[c] 'd'" This gives me Deccan as a way out. But the problem is that I want every word to start with d So, from the above example, I need a conclusion like Dean, New Delhi, Salam Delhi , but NOT Ahmedabad

Stuck in this watch issue. tried contains, matches, but my failure ..

Any help on the right path would really be appreciated.

+8
ios nspredicate
source share
3 answers

Thank you guys for your answers. That's what I came up with.

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

There are two ways for you.

  • Divide the rotation by '' and use NSPredicate *predicate = [NSPredicate predicateWithFormat:@"keyword BEGINSWITH[c] 'd'"]
  • Or, better, use two predicates:

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

So, you will satisfy both possible cases.

+1
source share

Consider "how" and "matches." Please note, however, that these are relatively expensive operations and can take considerable time on large datasets.

In this example, I assume that you want to combine if any word separated by a space starts with "d"

This checks if the keyword starts with 'd' or has a sequence with the sequence 'd'

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

In this case, a regular expression is used that is very similar (use the regular expression that best suits your situation:

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

All Articles