文字列をOR検索してヒット数を出す
また正規表現です。
今度はOR検索してヒット数を出してみました。
NSArray *ar = [NSArray arrayWithObjects:@"いち",@"いちご",@"いちごあめ",@"ガリガリ君",nil]; NSString *str = [ar componentsJoinedByString:@","]; NSError *error = nil; NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"(いち|あんず)" options:0 error:&error]; //OR検索ではなく単純に検索する場合は@"(いち)" NSMutableArray *hitarray = [[NSMutableArray alloc] init]; id proc = ^(NSTextCheckingResult *arresult, NSMatchingFlags flag, BOOL *stop) { [hitarray addObject: [str substringWithRange:[arresult rangeAtIndex:1]]]; }; [regexp enumerateMatchesInString:str options:0 range:NSMakeRange(0, str.length) usingBlock:proc]; int count = [hitarray count]; NSLog(@"%d",count);
追記:
もっと短くて済む方法があったので追記しました。
NSString *str = @"サウスパークおもろいよ!"; NSError *error = nil; NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"(おもろい|サウスパーク)" options:0 error:&error]; NSUInteger matchCount = [regexp numberOfMatchesInString:str options:0 range:NSMakeRange(0, [str length])]; NSLog(@"%d",matchCount);