2012-07-22 116 views
23

我有一個NSPredicate這樣的:NSPredicate精確匹配字符串與

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

但是,這將返回任何包含該字符串。例如: 如果我entity.name的地方:

text 
texttwo 
textthree 
randomtext 

myStringtext那麼所有這些字符串會匹配。我希望它如果myStringtext它只會返回名稱爲text的第一個對象,如果myStringrandomtext它將返回名稱爲randomtext的第四個對象。我還期待着爲它是區分大小寫,它忽略空白

回答

54

這應做到:

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

LIKE匹配字符串用?和*作爲通配符。 [c]表示比較應該不區分大小寫。

如果你不想要?和*被視爲通配符,您可以使用==代替LIKE:在NSPredicate謂詞格式字符串語法documentation

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

更多信息。

+0

它忽略空格嗎? – CoreCode 2012-07-22 03:31:35

+0

啊,對不起,我錯過了那部分。我認爲對於空白不敏感,您必須使用MATCHES並提供正則表達式而不是簡單的匹配字符串。 dasblinkenlight的答案證明了這一點。 – 2012-07-22 03:36:25

12

您可以使用正則表達式匹配您的斷言,這樣的:

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

上面的一段代碼構造開頭和/或結尾匹配帶有可選的空白字符串正則表達式,有由「字邊界」標記圍繞的目標字\bmatches之後的[c]表示「不區分大小寫」。

本示例使用字符串數組;使其在您的環境中工作,請將SELF替換爲entity.name