“Whole word” search in a NSString through NSPredicate

99封情书 提交于 2020-01-01 01:13:16

问题


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.)


回答1:


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.*"; 


来源:https://stackoverflow.com/questions/8559156/whole-word-search-in-a-nsstring-through-nspredicate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!