NSPredicate逐字匹配字符串

时间:2019-03-04 13:15:26

标签: ios objective-c swift nsstring nspredicate

我有一个字符串数组,如下所示:

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

如果我搜索“牛奶”,则结果应为["Milk","Milk Shake","Milk-Cream"],即按单词搜索。

谓词为

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

我从上面的数组中获取所有结果。如何使用单词进行比赛?

1 个答案:

答案 0 :(得分:3)

您需要“正则表达式搜索”来匹配单词边界,这是通过谓词中的“ MATCHES”完成的。这是一个示例(基本上是从NSPredicate with core data, search word with boundaries in string attribute转换为Swift的):

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

这将搜索tagName包含给定搜索词并被“单词边界”(\b模式)包围的所有条目。