Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching CoreData using regex and special characters

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?

like image 382
bryan Avatar asked Feb 13 '23 18:02

bryan


1 Answers

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.

like image 184
Martin R Avatar answered Feb 23 '23 03:02

Martin R