ios NSPredicate 与字符串完全匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11597508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSPredicate Exact Match with String
提问by CoreCode
I have a NSPredicate like this:
我有一个像这样的 NSPredicate:
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:
但这将返回包含该字符串的任何内容。例如:如果我的 entity.name 位于:
text
texttwo
textthree
randomtext
and the myStringwas textthen all of those strings would match. I would like it so that if myStringis textit would only return the first object with the name textand if myStringwas randomtextit would return the fourth object with the name randomtext. I am also looking for it to be case insensitiveand that it ignores whitespace
并且myString是text那么所有这些字符串会匹配。我希望这样,如果myString是,text它只会返回具有名称的第一个对象,text如果myString是randomtext,它将返回具有名称的第四个对象randomtext。我也在寻找它不区分大小写并且它忽略空格
回答by Andrew Madsen
This should do it:
这应该这样做:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"entity.name LIKE[c] %@", myString];
LIKEmatches strings with ? and * as wildcards. The [c]indicates that the comparison should be case insensitive.
LIKE匹配字符串?和 * 作为通配符。本[c]表示比较应不区分大小写。
If you don't want ? and * to be treated as wildcards, you can use ==instead of LIKE:
如果你不想?和 * 被视为通配符,您可以使用==代替LIKE:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"entity.name ==[c] %@", myString];
More info in the NSPredicate Predicate Format String Syntax documentation.
NSPredicate 谓词格式字符串语法文档中的更多信息。
回答by dasblinkenlight
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 matchesmeans "match case-insensitively".
上面的这段代码构建了一个正则表达式,它匹配开头和/或结尾带有可选空白的字符串,目标词被“词边界”标记包围\b。在[c]之后matches的意思是“匹配不区分大小写”。
This example uses an array of strings; to make it work in your environment, replace SELFwith entity.name.
这个例子使用了一个字符串数组;要使其在您的环境中工作,请替换SELF为entity.name.

