cocoa-touch - "Whole word"通过 NSPredicate 在 NSString 中搜索

标签 cocoa-touch core-data nsstring nspredicate nsfetchrequest

我想搜索属性 description(一个 NSString 实例)中是否有给定的单词。

我试过这个谓词:

[NSPredicate predicateWithFormat:@"description CONTAINS[cd] %@", theWord];

它有效,但它也会找到子词。

例如,给定 theWord :

Car



它也会处理这个 description :

A Christmas Carol



相反,我希望我的谓词只匹配 a 、或 christmascarol

(我正在使用核心数据和 NSFetchRequest。)

最佳答案

像这样的东西?

NSString *matchStr = @".*\\bCarol\\b.*";

NSPredicate *pred =[NSPredicate predicateWithFormat: @"description MATCHES %@", matchStr];

NSArray *arr = @[ 
    @"A Christmas Carol",
    @"Sing",
    @"Song"
];

NSArray *filtered = [arr filteredArrayUsingPredicate: pred];

诀窍是 \b 元字符,它表示字符串中的单词边界。为了将反斜杠“插入”正则表达式模式字符串,您必须在它前面加上另一个反斜杠,以便编译器知道字符串中应该有一个真正的反斜杠。因此字符串中的“\\b”。

此外,为了更好地覆盖非英语语言字符串,您应该通过设置 w 标志选项来启用 Unicode 词边界检测。匹配字符串将如下所示:
NSString *matchStr = @"(?w).*\\bCarol\\b.*"; 

关于cocoa-touch - "Whole word"通过 NSPredicate 在 NSString 中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8559156/

相关文章:

web-services - 使用 Objective C 进行 SOAP 查询

ios - 使用核心数据在 NSDate 属性中仅按年份过滤 TableView Controller

ios - 在 iOS 中将 NSString 转换为 unichar

html - 在 NSString 中搜索以特定文本开头并以 "结尾的单词

ios - AppDelegate 没有响应 NSNotification

ios - map 上的多个位置(使用 MKMapItem 和 CLGeocoder)

iphone - 让 UITableView 不在 UIScrollView 中滚动和增长

arrays - Swift - 将对象数组保存到核心数据,检索时只取回一个对象

ios - 核心数据和可转换检索图像

iphone - 如何查找 NSString 中某种格式的出现