NSPredcate与字符串完全匹配



我有一个类似的NSPredcate:

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

但这将返回包含该字符串的任何内容。例如:如果我的实体名称在哪里:

text
texttwo
textthree
randomtext

并且CCD_ 1是CCD_。我希望这样,如果myStringtext,它将只返回名称为text的第一个对象,而如果myStringrandomtext,它将返回名称为randomtext的第四个对象。我还希望它不区分大小写,并忽略空白

这应该做到:

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

LIKE将字符串与?匹配?和*作为通配符。myString0表示比较应该是不区分大小写的。

如果你不想?和*要被视为通配符,可以使用==而不是LIKE:

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

有关详细信息,请参阅NSPredcate谓词格式字符串语法文档。

您可以在谓词中使用正则表达式匹配器,如下所示:

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];

上面的代码构建了一个正则表达式,该表达式将字符串与开头和/或结尾的可选空格相匹配,目标单词由"单词边界"标记b包围。matches后面的[c]表示"不区分大小写匹配"。

此示例使用字符串数组;要使其在您的环境中工作,请将SELF替换为entity.name

最新更新