我需要使用NSPredicate匹配两个字符串,不区分大小写,变音符号不敏感,和空格不敏感。
谓词看起来像这样:
[NSPredicate predicateWithFormat:@"Key ==[cdw] %@", userInputKey];
'w'修饰符是一种发明的修饰语,用于表达我想要使用的内容。
我不能修剪userInputKey
,因为数据源“Key”值也可能包含空格(它们需要那些空格,我不能事先修剪它们)。
例如,给定userInputKey
“abc”,谓词应匹配所有
{"abc", "a b c", " a B C "},依此类推。给定
userInputKey
“a B C”,谓词也应匹配上述集合中的所有值。
这可不难做到,可以吗?
答案 0 :(得分:11)
如何定义这样的东西:
+ (NSPredicate *)myPredicateWithKey:(NSString *)userInputKey {
return [NSPredicate predicateWithBlock:^BOOL(NSString *evaluatedString, NSDictionary *bindings) {
// remove all whitespace from both strings
NSString *strippedString=[[evaluatedString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""];
NSString *strippedKey=[[userInputKey componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""];
return [strippedString caseInsensitiveCompare:strippedKey]==NSOrderedSame;
}];
}
然后像这样使用它:
NSArray *testArray=[NSArray arrayWithObjects:@"abc", @"a bc", @"A B C", @"AB", @"a B d", @"A bC", nil];
NSArray *filteredArray=[testArray filteredArrayUsingPredicate:[MyClass myPredicateWithKey:@"a B C"]];
NSLog(@"filteredArray: %@", filteredArray);
结果是:
2012-04-10 13:32:11.978 Untitled 2[49613:707] filteredArray: (
abc,
"a bc",
"A B C",
"A bC"
)
答案 1 :(得分:1)
Swift 4 :
func ignoreWhiteSpacesPredicate(id: String) -> NSPredicate {
return NSPredicate(block: { (evel, binding) -> Bool in
guard let str = evel as? String else {return false}
let strippedString = str.components(separatedBy: CharacterSet.whitespaces).joined(separator: "")
let strippedKey = id.components(separatedBy: CharacterSet.whitespaces).joined(separator: "")
return strippedString.caseInsensitiveCompare(strippedKey) == ComparisonResult.orderedSame
})
}
示例:
let testArray:NSArray = ["abc", "a bc", "A B C", "AB", "a B d", "A bC"]
let filteredArray = testArray.filtered(using: ignoreWhiteSpacesPredicate(id: "a B C"))
结果:
[“abc”,“a bc”,“A B C”,“A bC”]