我有一系列关键字和一个字符串数组。
我正在迭代关键字并在字符串数组上使用过滤器来确定关键字是否在那里(以某种形式)。
以下代码有效,但是当在另一个单词中有关键字(或与关键字相同的字符)时,会对其进行标记。即。在字符串功能区中搜索 bon 会标记功能区。我不想做一个精确的比较,因为关键字可能被字符串中的其他字符/单词包围。
有没有办法可以搜索它,只有当它被空格或括号包围时才标记它?即。不属于另一个词......
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]];
}
}
}
}
答案 0 :(得分: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];
}
}
}
答案 1 :(得分:0)
我猜regular expression就是你想要的。