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

时间:2015-12-03 21:21:20

标签: ios objective-c cocoa nspredicate

我有一个字符串数组:

@[@"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

我认为我不需要复合谓词,但我无法弄清楚如何将'数字'格式化为谓词字符串,以便它在'数字'中选择任何数字字符串。感谢。

1 个答案:

答案 0 :(得分:4)

您可以将简单的正则表达式传递给谓词,以匹配以数字开头的任何字符串。类似的东西:

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)
相关问题