So I'm trying to search through core data. Let's say my CoreData
has two fields which are NSString
(we'll call them foo & bar). The user gives an indication of which field to search and the search string. Right now I'm using this code:
NSString *format = [NSString stringWithFormat:@"(%@ matches[c] %@)", field, @"%@"];
// Double-escape that slash
NSString *pattern = [NSString stringWithFormat:@".*\\b%@.*", partialString];
NSPredicate *predicate = [NSPredicate predicateWithFormat:format, pattern];
[fetchRequest setPredicate:predicate];
Field is passed in as either "foo" or "bar". Partial string is the search string. If bar contains "Grand Poobah", I want it to match when "Poo" is the query string (but not when it's "oobah", that's why I have the \b in the regex).
But the issue I have is if someone gives a query of "Poo(" it crashes because it gets interpreted as part of the regex
.
Is the best route to simply escape all the special characters in partialString before building pattern? Or is there some other way I should be building the predicate?
Yes, you should escape all special characters in the search string, and there is an easy method to do so:
NSString *escapedString = [NSRegularExpression escapedPatternForString:partialString];
NSString *pattern = [NSString stringWithFormat:@".*\\b%@.*", escapedString];
But you should not use stringWithFormat
to build a predicate format string (as in your
first line). Simply continue
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K MATCHES[c] %@", field, pattern];
Note that %K
the predicate format must be used for a key path substitution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With