CoreData search using regular expressions and special characters

So, I am trying to search the master data. Say mine CoreDatahas two fields that NSString(we will call them foo and bar). The user gives an indication of which field to search and the search string. I am using this code now:

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];

The field is passed as "foo" or "bar". A partial string is a search string. If bar contains "Grand Poobah", I want it to match when "Poo" is the query string (but not when it is "oobah", so I have \ b in the regex).

But the problem I have is if someone gives the request "Poo (" it crashes because it is interpreted as part regex.

Is the best route to simply remove all special characters in partialString before creating the template? Or is there another way I have to build a predicate?

+4
source share
1 answer

Yes, you should avoid all special characters in the search bar, and there is an easy way to do this:

NSString *escapedString = [NSRegularExpression escapedPatternForString:partialString];
NSString *pattern = [NSString stringWithFormat:@".*\\b%@.*", escapedString];

But you should not use stringWithFormatpredicate formatting (as in your first line) to build a string. Just keep going

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K MATCHES[c] %@", field, pattern];

Note that %Kthe predicate format must be used to replace the key path.

+7
source

Source: https://habr.com/ru/post/1527789/


All Articles