2012-01-27 7 views
1

述語でXcode関数フィルタリングを実装したいと考えています。 Xcodeで関数名をフィルタリングすると、 "myFunc"によって、正確な文字列ではなくその文字列が検索されます。値にXcodeフィルタリングなどの文字列が含まれている述語を作成する方法

例:

momsYellowFunCar
メートルYFUNC

私はMATCHESを使用して、いくつかの方法を正規表現を提供する必要がありますか?

答えて

2

これは、10.7+とiOS 4.0+に組み込まれているNSRegularExpressionを使用して行うことができます。以下のような何か:

NSArray *stringsToSearch = [NSArray arrayWithObjects:@"mYFunC", @"momsYellowFunCar", @"Hello World!", nil]; 
NSString *searchString = @"mYFunC"; 
NSMutableString *regexPattern = [NSMutableString string]; 
for (NSUInteger i=0; i < [searchString length]; i++) { 
    NSString *character = [searchString substringWithRange:NSMakeRange(i, 1)]; 
    [regexPattern appendFormat:@"%@.*", character]; 
} 
NSError *error = nil; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexPattern 
                     options:NSRegularExpressionDotMatchesLineSeparators 
                     error:&error]; 
if (!regex) { 
    NSLog(@"Couldn't create regex: %@", error); 
    return; 
} 

NSMutableArray *matchedStrings = [NSMutableArray array]; 
for (NSString *string in stringsToSearch) { 
    if ([regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, [string length])] > 0) { 
     [matchedStrings addObject:string]; 
    } 
} 

NSLog(@"Matched strings: %@", matchedStrings); // mYFunC and momsYellowFunCar, but not Hello World! 

あなたがNSPredicateを使用する必要がある場合、あなたは-[NSPredicate predicateWithBlock:]でこのコードのバリエーションを使用することができます。

+0

ありがとうございました。私はすべてのコードを期待していませんでした。大変感謝しています。 – joels

関連する問題