2013-10-18 61 views
0

我有NSArrayNSStrings,我想要做的是例如尋找與R作爲第一個字符和A作爲第三個8字符的字符串。如何在NSArray中查找可能的字符串?

在SQL我會做這樣的:

SELECT string FROM array WHERE string LIKE 'R*A*****'; 

但我不什麼在對象 - 這樣做的最佳途徑的想法。當然,我可以用characterAtIndex:創建一個檢查字符的函數,但我確定有一些更快的方法可以像正則表達式一樣進行。

感謝您的幫助。

+0

爲什麼你認爲正則表達式會更快? –

+0

這只是一個猜測,我可能是錯的。 – Rob

回答

3

最簡單的方法可能只是使用indexesOfObjectsPassingTest:,並定義一個只檢查您關心的兩個字符的塊。喜歡的東西:

NSIndexSet *indexes = [array indexesOfObjectsPassingTest: 
    ^(id obj, NSUInteger idx, BOOL *stop) 
    { 
     if (([obj length] == 8) && 
      ([obj characterAtIndex:0] == 'R') && 
      ([obj characterAtIndex:2] == 'A')) 
      return YES; 
     else 
      return NO; 
    } 
]; 
2

只是爲了完整起見:類似於SQL查詢模式匹配的方法 是

NSPredicate *predicate = 
      [NSPredicate predicateWithFormat:@"SELF LIKE %@", @"R?A?????"]; 
NSArray *filtered = [array filteredArrayUsingPredicate:predicate]; 

但快速測試結果表明,基於塊的濾波作爲卡爾的回答至少在這種情況下更快, 。

1

使用characterAtIndex是最簡單的選擇,但如果你真的想使用正則表達式模式匹配,那麼這種模式可能會有所幫助。

for(int i=0;i<[array count];i++)  //'array' is the nsarray with collection of strings 
{ 
    string = [array objectAtIndex:i]; //'string' takes each string from the array 
    NSRegularExpression* reg=[NSRegularExpression regularExpressionWithPattern:@"R[a-zA-Z]{1}A[a-zA-Z]{5}" options:0 error:&error]; 

    NSTextCheckingResult *match=[reg firstMatchInString:string options:0 range:NSMakeRange(0, [string length])]; 

    NSLog(@"result is %@",[string substringWithRange:[match rangeAtIndex:0]]);    


} 

希望它有助於!

相關問題