正如 Tim 所说,我们可以使用正则表达式来匹配包含i
or的文本ı
。当搜索查找大量字符串时,我也不想添加新字段或更改源数据。所以我最终使用正则表达式和NSPredicate
.
创建NSString
类别并复制此方法。它返回基本or
匹配模式。您可以将它与任何接受正则表达式模式的方法一起使用。
- (NSString *)zst_regexForTurkishLettersWithCaseSensitive:(BOOL)caseSensitive
{
NSMutableString *filterWordRegex = [NSMutableString string];
for (NSUInteger i = 0; i < self.length; i++) {
NSString *letter = [self substringWithRange:NSMakeRange(i, 1)];
if (caseSensitive) {
if ([letter isEqualToString:@"ı"] || [letter isEqualToString:@"i"]) {
letter = @"[ıi]";
} else if ([letter isEqualToString:@"I"] || [letter isEqualToString:@"İ"]) {
letter = @"[Iİ]";
}
} else {
if ([letter isEqualToString:@"ı"] || [letter isEqualToString:@"i"] ||
[letter isEqualToString:@"I"] || [letter isEqualToString:@"İ"]) {
letter = @"[ıiIİ]";
}
}
[filterWordRegex appendString:letter];
}
return filterWordRegex;
}
因此,如果搜索词是Şırnak
,它会创建Ş[ıi]rnak
区分大小写和Ş[ıiIİ]rnak
不区分大小写的搜索。
以下是可能的用法。
NSString *testString = @"Şırnak";
// First create your search regular expression.
NSString *searchWord = @"şır";
NSString *searchPattern = [searchWord zst_regexForTurkishLettersWithCaseSensitive:NO];
// Then create your matching pattern.
NSString *pattern = searchPattern; // Direct match
// NSString *pattern = [NSString stringWithFormat:@".*%@.*", searchPattern]; // Contains
// NSString *pattern = [NSString stringWithFormat:@"\\b%@.*", searchPattern]; // Begins with
// NSPredicate
// c for case insensitive, d for diacritic insensitive
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self matches[cd] %@", pattern];
if ([predicate evaluateWithObject:testString]) {
// Matches
}
// If you want to filter an array of objects
NSArray *matchedCities = [allAirports filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:@"city matches[cd] %@", pattern]];
您也可以使用NSRegularExpression
,但我认为使用大小写和变音符号不敏感搜索NSPredicate
要简单得多。