gpt4 book ai didi

ios - 使用*作为Realm中 'LIKE'的常规字符过滤对象

转载 作者:行者123 更新时间:2023-11-30 11:47:40 25 4
gpt4 key购买 nike

我尝试查找包含带有通配符的子字符串的字符串。在下面的示例中,字符串应确认模式(任何符号 '*' 任何符号 'p' 任何符号) 。我尝试使用此代码从 Realm 中搜索对象

class ServiceMessage: Object {
@objc dynamic var desc = ""
}

let realm = try! Realm()

let dataSource = [
"Domain CheckService",
"IMEI check",
"Compliant about service provider",
"Compliant about TRA",
"Enquires",
"Suggestion",
"SMS* S[pam",
"Poor Coverage",
"Pure *Signal",
"Help Salim"
]

for text in dataSource {
let sm = ServiceMessage()
sm.desc = text;
try! realm.write {
realm.add(sm)
}
}


let searchString = "*\\**p*"
let predicate = NSPredicate(format: "SELF.desc LIKE[c] %@", searchString)
let errors = realm.objects(ServiceMessage.self).filter(predicate)

我什么也没得到。如果我尝试使用此谓词过滤简单的字符串数组,一切都会正常工作。有人知道这个问题的解决方案吗?我尝试在 LIKE 之后添加 [w],但这对我没有帮助。

最佳答案

这里的主要问题是您不能在 Realm 中使用正则表达式作为谓词,我们可以在此处阅读 https://github.com/realm/realm-cocoa/issues/2629正确的方法应该是

let realmInstance = try? Realm()
let expresion = ".*\\*.*p.*"
let predicate = NSPredicate(format: "SELF.name MATCHES %@", expresion)
self.realmArrayDogs = realmInstance?.objects(Dog.self).filter(predicate)

但这会因以下错误而崩溃

Terminating app due to uncaught exception 'Invalid operator type', reason: 'Operator 'MATCHES' not supported for string type'

这是使用 stringArray 进行相同操作的示例

let array = ["D*usadpdasd","probando","asdasd*ffffpppp"]
do{
let expresion = ".*\\*.*p.*"
let predicate = NSPredicate(format: "SELF MATCHES %@",expresion)
let resultArray = array.filter({predicate.evaluate(with: $0)})
debugPrint(resultArray)
}
catch
{

}

作为解决方法,您可以将结果从 Realm 转换为数组,然后使用谓词进行过滤

这有效!

let realmInstance = try? Realm()
let expresion = ".*\\*.*p.*"
let predicate = NSPredicate(format: "SELF.name MATCHES %@", expresion)
let arrayOfDogsResult = realmInstance?.objects(Dog.self)
let filteredArray = Array(arrayOfDogsResult!).filter({predicate.evaluate(with: $0)})
debugPrint(filteredArray)

关于ios - 使用*作为Realm中 'LIKE'的常规字符过滤对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48642271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com