How to find beginswith word in a string using NSPredicate?
I am searching for a solution on how to format NSPredicate to search correct word in a string of text. Currently I am using this code:
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"(content CONTAINS[c] %@)", word];
but it returns wrong resuls if the word is short, for example: if the word is 'ail' it will return all strings with words which include this 3 letters.. But I don't need such开发者_高级运维 abstract search, so how to search words 'beginswith' my word in a string?
Simply use BEGINSWITH
instead of CONTAINS
.
Edit
If you need to search in every word of a string, there is a technique which was presented in one of the talks in WWDC 2010. The basic idea is to create a separate entity Word
which contains a single word and a reference of the containing object (the entity you're searching). You then do the search on the Word
entity and return the objects which are related to the found words.
The query would then look something like this (provided you have a many-to-one relationship between your entity and Word
: "ANY words BEGINSWITH[c] %@"
This would mean that you have to setup the words when creating your objects though.
search first with BEGINSWITH
for "Foo", this will find you the beginnings of a string
"Foo Word1 Word2", "Foo OtherWord1 OtherWord2" (will find 2)
and than CONTAINS
for " Foo" (note the space before Foo), which will give you words that starts with "Foo" presided with a space
"Word1 Foo Word", "Some OtherWord FooWord", "Misc FooXWord" (will find 3)
Predicate :
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"(content BEGINSWITH[c] %@) OR (content CONTAINS[c] %@)", word, [NSString stringWithFormat:@" %@", word]];
If your text contains some punctuation chars between words you may use this predicate:
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"(name BEGINSWITH[c] %@) OR (name MATCHES[c] %@)",
query,
[NSString stringWithFormat:@".*[^\\w]%@.*", query]];
I've had the same issue and at first i thought your answers could help me, but they didn't. This one helped me, so...Take a look:
NSString *matchString = [NSString stringWithFormat: @".*\\b%@.*",searchText];
NSString *predicateString = @"keyword MATCHES[c] %@";
NSPredicate *predicate =[NSPredicate predicateWithFormat: predicateString, matchString];
Try using compound:
NSCompoundPredicate *bPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[[NSPredicate predicateWithFormat:@"content BEGINSWITH[cd] %@",_SearchBar.text], [NSPredicate predicateWithFormat:@"content CONTAINS[cd] %@", _SearchBar.text]]];
精彩评论