In Swift 4 I have a CoreData \"Sentence\" model that has a String attribute \"englishsentence\". I also have an array of \"words\" and would like to fetch all sentences for
One option would be to create a “compound predicate:”
let words = ["today", "yesterday", "tomorrow"]
let predicates = words.map {
NSPredicate(format: "englishsentence CONTAINS %@", $0)
}
let predicate = NSCompoundPredicate(orPredicateWithSubpredicates: predicates)
Another option is to match against a regular expression:
let regex = ".*(" + words.map {
NSRegularExpression.escapedPattern(for: $0)
}.joined(separator: "|") + ").*"
let predicate = NSPredicate(format: "englishsentence MATCHES %@", regex)
To match only “whole words” you can add the word boundary pattern \b
:
let regex = ".*\\b(" + words.map {
NSRegularExpression.escapedPattern(for: $0)
}.joined(separator: "|") + ")\\b.*"