2

I have an array of strings as below:

["Milk","Milkshake","Milk Shake","MilkCream","Milk-Cream"]

and if I search for "milk" then results should be ["Milk","Milk Shake","Milk-Cream"] i.e. search by words.

With the predicate as

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"tagName CONTAINS[c] %@",containSearchTerm];

I am getting all the results from above array. How can I perform match using words ?

nikksindia
  • 1,147
  • 1
  • 10
  • 18

1 Answers1

6

You need a “regular expression search” in order to match against word boundaries, that is done with "MATCHES" in a predicate. Here is an example (essentially translated from NSPredicate with core data, search word with boundaries in string attribute to Swift):

let searchTerm = "milk"
let pattern = ".*\\b\(NSRegularExpression.escapedPattern(for: searchTerm))\\b.*"
let predicate = NSPredicate(format: "tagName MATCHES[c] %@", pattern)

This searches for all entries where the tagName contains the given search term, surrounded by a “word boundary” (the \b pattern).

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382