NSPredicate搜索LIKE

Mai*_*639 0 objective-c nspredicate ios

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

[NSPredicate predicateWithFormat:@"SELF LIKE[c] '#*!%d'", aNumber]
Run Code Online (Sandbox Code Playgroud)

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

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

编辑:

NSString *pattern = [@"#*!" stringByAppendingFormat:@"%d", numberVariable];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
NSArray *filteredArray = [anArray filteredArrayUsingPredicate:pred];
Run Code Online (Sandbox Code Playgroud)

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

编辑:

我的解决方案

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

Mar*_*n R 5

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

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"#.*!\\d+"];
NSArray *filtered = [yourArray filteredArrayUsingPredicate:pred];
Run Code Online (Sandbox Code Playgroud)

如果您有一个特定的数字aNumber并想要找到"#ANY_CHARACTERS!<aNumber>"形式的所有字符串,那么以下内容应该有效:

NSString *pattern = [@"#*!" stringByAppendingFormat:@"%d", aNumber];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF LIKE %@", pattern];
NSArray *filtered = [yourArray filteredArrayUsingPredicate:pred];
Run Code Online (Sandbox Code Playgroud)

你的问题

[NSPredicate predicateWithFormat:@"SELF LIKE[c] '#*!%d'", aNumber]
Run Code Online (Sandbox Code Playgroud)

%d 引号内部没有被替换aNumber.