NSPredicate搜索LIKE

时间:2013-06-01 17:54:01

标签: ios objective-c nspredicate

我正在尝试使用此谓词过滤字符串数组:

[NSPredicate predicateWithFormat:@"SELF LIKE[c] '#*!%d'", aNumber]

每个字符串都像#WILDCARD!ANY_NUMBER一样有效。

但它不起作用:( 你能救我吗?

编辑:

NSString *pattern = [@"#*!" stringByAppendingFormat:@"%d", numberVariable];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
NSArray *filteredArray = [anArray filteredArrayUsingPredicate:pred];

数组anArray包含#0!-1(numberVariable为-1)等字符串,但数组filterdArray为空。所以正则表达式不起作用。

编辑:

我的解决方案:

NSString *pattern = [@"#.*!\\" stringByAppendingFormat:@"%d", numberVariable];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
NSArray *filteredArray = [anArray filteredArrayUsingPredicate:pred];

1 个答案:

答案 0 :(得分:5)

要查找所有看起来像“#ANY_CHARACTERS!ANY_NUMBER”且任意数的字符串,您需要带有正则表达式的“MATCHES”运算符:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"#.*!\\d+"];
NSArray *filtered = [yourArray filteredArrayUsingPredicate:pred];

如果您有特定号码aNumber,并希望查找表单的所有字符串 “#ANY_CHARACTERS!< aNumber>”,然后以下内容应该有效:

NSString *pattern = [@"#*!" stringByAppendingFormat:@"%d", aNumber];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF LIKE %@", pattern];
NSArray *filtered = [yourArray filteredArrayUsingPredicate:pred];

的问题
[NSPredicate predicateWithFormat:@"SELF LIKE[c] '#*!%d'", aNumber]

引号内的%d 未被aNumber取代。