Search code examples
iosobjective-cswiftnsstringnspredicate

NSPredicate match string by words


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 ?


Solution

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