问题
I feel like the answer to my question might already be somewhere on this forum, but after hours of scouring I just can't quite seem to get it right. I've never used SQL before so please bear with me.
I have a core data model with only one entity and that entity has an attribute called "definitions" (each entity in the database is a dictionary entry). What I want to do is search the definitions for an input string with word boundaries. If I do a simple CONTAINS[cd]
search with NSPredicate and the input text I get what I'm looking for, except that I also get definitions that contain the input sequence of characters, regardless of boundaries.
So I've also tried building a regex string like @"(?w).*\\btheWord\\b.*"
, along with the MATCHES[cd]
search command, but I read on other posts that can only be used when searching NSStrings, and regardless it didn't work.
This should be simple but I'm stumped. Any help appreciated.
EDIT : Here's an example of what I'm doing
YTAppDelegate * delegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext * context = delegate.managedObjectContext;
NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"YTDictData"];
NSString * searchTerm = [NSString stringWithFormat:@"'(?w).*\\b%@\\b.*'",[NSRegularExpression escapedPatternForString:inputText]];
NSString * searchString = [NSString stringWithFormat:@"definitions contains[cd] %@",searchTerm];
request.predicate = [NSPredicate predicateWithFormat:searchString];
NSError * searchError = nil;
NSArray * searchResults = [context executeFetchRequest:request error:&searchError];
In this case, if I were to search for the word "hello", I would get no matches.
However if I do not format the searchString
string for regex searching (ie searchString = inputString
), I will get any definition that contains the sequence of characters "hello". I need to be able to find strings which contain the string "hello", but I also need the added constraint that I want "hello" to be recognized as a word with boundaries.
回答1:
As already said in the comments, you have to use the "MATCHES" operator
for regular expression matching. In addition, you should not use
stringWithFormat
to build the predicate string (your searchString
variable).
This is how it should work:
NSString *searchTerm = [NSString stringWithFormat:@".*\\b%@\\b.*",
[NSRegularExpression escapedPatternForString:inputText]];
request.predicate = [NSPredicate predicateWithFormat:@"definitions MATCHES[cd] %@",
searchTerm];
来源:https://stackoverflow.com/questions/28104948/nspredicate-with-core-data-search-word-with-boundaries-in-string-attribute