忽略空格的NSPredicate

9

我需要使用NSPredicate来匹配两个字符串,不区分大小写、不考虑变音符号和空格。

谓词应该像这样:

[NSPredicate predicateWithFormat:@"Key ==[cdw] %@", userInputKey];

'w'修饰符是我想使用的一种发明。

我不能仅仅修剪userInputKey,因为数据源“Key”值中可能也有空格(它们需要这些空格,我不能事先修剪它们)。

例如,给定一个userInputKey“abc”,谓词应匹配所有

{"abc", "a b c", " a B    C   "}
等。给定一个userInputKey“a B C”,谓词也应匹配上述集合中的所有值。

这不可能很难做到,对吗?

2个回答

13

那我们定义一个类似这样的东西如何:

+ (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"
)

我不得不查找https://dev59.com/zHA65IYBdhLWcg3w9DmF,因为我想在NSFetchRequest中使用谓词,但除此之外,你的解决方案非常好。谢谢! - JiaYow

2

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")) 

Result:

["abc", "a bc", "A B C", "A bC"]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接