簡體   English   中英

NSPredicate 檢查以逗號分隔的一串數字是否包含數字

[英]NSPredicate to check whether a string of numbers separated by comma contains a number

我的核心數據中有一個字符串說"0,1,2,3,4,5,6,7,8,9,10,11" (假設是月份索引字符串)。 我想使用謂詞來獲取該字段是否包含數字,比如字符串包含“0”。

我們不能使用 'CONTAINS',因為 '0' 也存在於 '10' 中。 我需要使用NSPredicate獲取對象以避免來自 Core Data 的循環。

更新:我只想測試 '0,1,2,3,4,5,6,7,8,9,10,11' 是否包含 '0' 或不使用NSPredicate

解決了

NSPredicate的“MATCHES”運算符可用於與正則表達式進行比較:

NSString *searchTerm = @"0";
NSString *regex = [NSString stringWithFormat:@"(.*,)?%@(,.*)?", searchTerm];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"strIndex MATCHES %@", regex];

這對我來說很好。 謝謝@skagedal 的建議。 從包含 id 的字符串的 Form NSPredicate得到了這個答案。

@bunty 的答案是直接正確的,但有一個元答案。

您可能應該有一個 Months 實體,其中包含數據存儲中一年中的 12 個月。 然后,從包含該字符串的事物到 Months 實體建立一對多(根據需要排序或不排序)關系。

然后,您只需按照關系(即myThing.months )獲取實體需要的月份。

對於大型數據庫,使用字符串匹配謂詞的提取會非常慢,而且確實有點反模式。

您可以使用正則表達式檢查以逗號分隔的數字,如下所示:

NSString *str = @"0,1,2,3,4,5,6,7,8,9,10,11";
NSString *regex = @"(\\d+)(,\\s*\\d+)*";
NSPredicate *myTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

if ([myTest evaluateWithObject: str])
    NSLog(@"matched");
else
    NSLog(@"not matched");

因此,在從具有字段名稱的核心數據中獲取數據時使用此謂詞,如下所示:

NSError* error = nil;
NSString *regex = @"(\\d+)(,\\s*\\d+)*";
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"TableName" inManagedObjectContext:context];
[fetchRequest setEntity:entity];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"MonthFieldName MATCHES %@", regex];
[fetchRequest setPredicate:predicate];
NSArray* arrRecords = [context executeFetchRequest:fetchRequest error:&error];

正如 bunty 所寫,您可以使用正則表達式。 如果我理解這個問題,您需要一個查找特定數字字符串的謂詞 - 但前提是不直接在其他數字之前或之后。 這可以通過正則表達式中稱為后前瞻斷言的方法來實現 更具體地說,消極的后視/前瞻斷言。

查看 NSPredicate 使用的正則表達式語法 要搜索數字1而不同時找到1110 ,請使用正則表達式:

(?<!\d)1(?!\d)

因此,您可以使用以下內容構建 Core Data 謂詞:

NSString *month = @"11"; // the number you're looking for
NSString *regex = [NSString stringWithFormat:@"(?<!\d)%@(?!\d)", month];
NSPredicate *myTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

這不會是一個非常有效的搜索,但是如果這就是您的 Core Data 模型的樣子並且您無法輕松更改它,那么它可能會正常工作。 如果可以,我會采納 bbum 的建議並重新組織您的模型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM