我正在尝试使用此谓词过滤字符串数组:
[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];
答案 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
取代。