“全字”通过NSPredicate在NSString中搜索 [英] "Whole word" search in a NSString through NSPredicate

查看:161
本文介绍了“全字”通过NSPredicate在NSString中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我尝试使用此谓词:

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

它可以工作,但也会找到子字



例如,给定 theWord


汽车


它也会


圣诞颂歌


我的谓词只匹配 a christmas carol



(我使用Core Data和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 元字符,其表示字符串中的字边界。为了得到一个反斜杠into正则表达式模式字符串,你必须在它之前有另一个反斜杠,所以编译器理解在字符串中应该有一个真正的反斜杠。因此,字符串中的\\b。



此外,为了更好地覆盖非英语字符串,您应该启用Unicode字边界检测,设置 w 标志选项。匹配字符串将如下所示:

  NSString * matchStr = @(?w)。* \\bCarol\\ \\\b。*; 


I would like to search if in the attribute description (an NSString instance) there is a given word.

I tried with this predicate:

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

It works, but it finds also sub-words.

For example, given theWord:

Car

it will mach also this description:

A Christmas Carol

Instead, I would like that my predicate will match only a, or christmas, or carol.

(I'm using Core Data and NSFetchRequest.)

解决方案

Something like this?

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

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

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

NSArray *filtered = [arr filteredArrayUsingPredicate: pred];

The trick is the \b metacharacter, which denotes a word boundary in the string. In order to get a backslash "into" the regex pattern string, you have to precede it with another backslash so the compiler understands that there should be a real backslash in the string. Hence the "\\b" in the string.

Also, in order to cover non-English language strings better, you should enable Unicode word boundary detection, by setting the w flag option. The match string will look like this:

NSString *matchStr = @"(?w).*\\bCarol\\b.*"; 

这篇关于“全字”通过NSPredicate在NSString中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆