我尝试查找包含带通配符的子字符串的字符串。在以下示例中,字符串应确认模式 (任何符号' *'任何符号' 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]它对我没有帮助。
答案 0 :(得分:0)
这里的主要问题是你不能在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)
但会因以下错误而崩溃
由于未捕获的异常而终止应用“无效的运算符类型”, 原因:字符串类型'
不支持'运算符'匹配'
这是使用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转换为Array,然后使用谓词
进行过滤这有效!
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)