0

我有一个关键字数组和一个字符串数组

我目前正在迭代关键字并在字符串数组上使用过滤器来确定关键字是否在其中(以某种形式)。

下面的代码有效,但是当另一个单词中有关键字(或与关键字相同的字符)时,就会被标记。IE。在字符串功能区中搜索bon将标记功能区。我不想进行精确比较,因为关键字可能会被字符串中的其他字符/单词包围。

有没有一种方法可以搜索它并且只在它被空格或括号包围时才标记它?IE。不是另一个词的一部分..

NSArray *paInc = [productIncludes valueForKey:pa];
// This is the array of keywords

NSMutableArray *paMatchedIncludes = [[NSMutableArray alloc] init];

for (id include in paInc){

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [cd] %@", include];
    NSArray *filteredArray = [stringArray filteredArrayUsingPredicate:predicate];
    // stringArray is the array containing the strings I want to search for these keywords

    for (NSString *ing in filteredArray){
        if ([ing length] > 0){
            if (![paMatchedIncludes containsObject:[NSString stringWithFormat:@"%@",ing]]){
                [paMatchedIncludes addObject:[NSString stringWithFormat:@"%@",ing]];
            }
        }
    }

}
4

2 回答 2

1

下面的代码能解决你的问题吗?

NSArray *paInc = @[@"bon",
                   @"ssib"];
// This is the array of keywords

NSArray *stringArray = @[@"Searching for bon in string ribbon would flag ribbon.",
                         @"I don't want to do an exact comparison as it's possible the keyword will be surrounded by other characters / words in the string."];
// stringArray is the array containing the strings I want to search for these keywords

NSMutableArray *paMatchedIncludes = [[NSMutableArray alloc] init];

for (id include in paInc){ // for every keyword
    for (NSString *nextString in stringArray) { // for every string
        NSArray *components = [nextString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" ()"]];
        if ([components containsObject:include]) {
            [paMatchedIncludes addObject:nextString];
        }
    }
}

编辑(由于您的评论):对于不区分大小写的比较:

for (id include in paInc){ // for every keyword
    for (NSString *nextString in stringArray) { // for every string
        NSArray *components = [nextString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" ()"]];
        for (NSString *nextComponent in components) {
            if([nextComponent caseInsensitiveCompare:include] == NSOrderedSame)
                [paMatchedIncludes addObject:nextString];
        }
    }
}
于 2013-09-20T08:16:34.047 回答
0

我想正则表达式是你想要的。

于 2013-09-20T07:28:50.800 回答