NSPredicate Exact Match with String

走远了吗. 提交于 2019-11-27 05:42:26

问题


I have a NSPredicate like this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"entity.name CONTAINS %@", myString];

But that will return anything which contains that string. For example: If my entity.name's where:

text
texttwo
textthree
randomtext

and the myString was text then all of those strings would match. I would like it so that if myString is text it would only return the first object with the name text and if myString was randomtext it would return the fourth object with the name randomtext. I am also looking for it to be case insensitive and that it ignores whitespace


回答1:


This should do it:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"entity.name LIKE[c] %@", myString];

LIKE matches strings with ? and * as wildcards. The [c] indicates that the comparison should be case insensitive.

If you don't want ? and * to be treated as wildcards, you can use == instead of LIKE:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"entity.name ==[c] %@", myString];

More info in the NSPredicate Predicate Format String Syntax documentation.




回答2:


You can use regular expression matcher with your predicate, like this:

NSString *str = @"test";
NSMutableString *arg = [NSMutableString string];
[arg appendString:@"\\s*\\b"];
[arg appendString:str];
[arg appendString:@"\\b\\s*"];
NSPredicate *p = [NSPredicate predicateWithFormat:@"SELF matches[c] %@", arg];
NSArray *a = [NSArray arrayWithObjects:@" test ", @"test", @"Test", @"TEST", nil];
NSArray *b = [a filteredArrayUsingPredicate:p];

The piece of code above constructs a regular expression that matches strings with optional blanks at the beginning and/or at the end, with the target word surrounded by the "word boundary" markers \b. The [c] after matches means "match case-insensitively".

This example uses an array of strings; to make it work in your environment, replace SELF with entity.name.



来源:https://stackoverflow.com/questions/11597508/nspredicate-exact-match-with-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!