NSPredicate 按数组中包含的第一个字母过滤

NSPredicate filter by first letter that is contained in an array

我有一个字符串数组:

@[@"ballot", @"1-time", @"32marks", @"zoo"];

我需要一个谓词来查找所有以数字开头的字符串。所以过滤后的数组应该是:

@[@"1-time", @"32marks"]

这是我目前正在尝试的:

data = @[@"ballot", @"1-time", @"32marks", @"zoo"];
NSArray *numbers = @[@"0", @"1", @"2", @"3", @"4", @"5",@"6", @"7"];
NSPredicate *firstPredicate = [NSPredicate predicateWithFormat:@"ANY %K IN %@", numbers];
NSPredicate *secondPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH"];

NSCompoundPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:
                                      @[firstPredicate, secondPredicate]];

data = [data filteredArrayUsingPredicate:predicate];

它崩溃了:

-[__NSArrayI rangeOfString:]: unrecognized selector sent to instance 0x15fc99a0

我认为我不需要复合谓词,但我不知道如何将 'numbers' 格式化为谓词字符串,以便它选择 'numbers' 中的任何数字字符串。谢谢

您只需将一个简单的正则表达式传递给谓词即可匹配任何以数字开头的字符串。类似于:

NSArray *data = @[@"ballot", @"1-time", @"32marks", @"zoo"];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"^\d.+"];
// Or ^\d(.+)? if you want to match single-digit numbers also

data = [data filteredArrayUsingPredicate:predicate];

NSLog(@"%@", data); // Outputs: ("1-time", 32marks)