CoreData Predicate get every sentence that contains any word in array

前端 未结 1 1258
醉话见心
醉话见心 2021-01-20 00:28

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

相关标签:
1条回答
  • 2021-01-20 01:12

    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.*"
    
    0 讨论(0)
提交回复
热议问题