NSPredicate 用于过滤带有 ( ' ) 字符问题的数组

NSPredicate for filtering array with ( ' ) character issue

这是我通过字符串过滤数组的测试。如果我的字符串不包含 (') 字符

,它会很好地工作
    NSMutableArray *array = [NSMutableArray arrayWithObjects:@"Nick", @"b'en", @"Adam", @"Melissa", @"arbind", nil];

    //NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'b'"]; -> it work
    NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'b''"]; -> it crash
    NSArray *beginWithB = [array filteredArrayUsingPredicate:sPredicate];
    NSLog(@"beginwithB = %@",beginWithB);

我也尝试将我的字符串更改为 'b\'''b''' 但它仍然崩溃

这是崩溃日志

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "SELF contains[c] 'b'''"'

如何解决?任何帮助将不胜感激。

试试这个

NSString *searchword = @"b";
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",searchword];

你得到

的输出

请尝试按如下方式过滤结果:

    NSMutableArray *array = [NSMutableArray arrayWithObjects:@"Nick", @"b'en", @"Adam", @"Melissa", @"arbind", nil];
        NSString *strToBeSearched = @"b'";

        //NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'b'"]; -> it work

        NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",strToBeSearched]; //-> it also work

        //OR

        NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'b\''"];


        NSArray *beginWithB = [array filteredArrayUsingPredicate:sPredicate];
        NSLog(@"containB = %@",beginWithB);

当你尝试反斜杠时,你已经非常接近了。这是 NSPredicate 用来转义特殊字符的字符。但是,您需要两个而不是一个反斜杠:

NSMutableArray *array = [NSMutableArray arrayWithObjects:@"Nick", @"b'en", @"Adam", @"Melissa", @"arbind", nil];
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'b\''"];
//                                                                              ^^
NSArray *beginWithB = [array filteredArrayUsingPredicate:sPredicate];
NSLog(@"beginwithB = %@",beginWithB);

您需要两个的原因是 Objective-C 编译器。它处理代码中的所有字符串文字,并替换它遇到的转义序列。如果您希望 NSPredicate 看到单个反斜杠,您的字符串文字需要有两个反斜杠,因为反斜杠本身在 Objective-C 字符串文字中被编码为 \

如果你的名字叫 b'en,

 NSString *name = @"b'en";
 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == \"%@\"", name];

希望这会有所帮助:)