NSPredicate that ignores whitespaces

前端 未结 2 1404
不思量自难忘°
不思量自难忘° 2021-02-15 15:06

I need to use NSPredicate to match two strings, case-insensitive, diacritic insensitive, and whitespace-insensitive.

The predicate would look something

相关标签:
2条回答
  • 2021-02-15 15:34

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

    Example:

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

    0 讨论(0)
  • 2021-02-15 15:42

    How about defining something like this:

    + (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;
        }];
    }
    

    Then use it like this:

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

    The result is:

    2012-04-10 13:32:11.978 Untitled 2[49613:707] filteredArray: (
        abc,
        "a bc",
        "A B C",
        "A     bC"
    )
    
    0 讨论(0)
提交回复
热议问题