NSPredicate Regex error - ios

I'm dealing with a document management page. I used NSPredicate regular expression while got the searchBar.text from user inputs. An error occurred (as the image below) while the inputs are brackets in Chinese form but went well in English form. If anyone has come across this matter? Thank you.
Here is my code,crash happen to the last row.
NSString * searchStr = [NSString stringWithFormat:#"fileName like[cd] \'*%#*\'",searchDisplayController.searchBar.text];
NSPredicate *predicate = [NSPredicate predicateWithFormat:searchStr];
self.fileArrayAfterPre = [[NSMutableArray alloc] initWithArray:[fileArr filteredArrayUsingPredicate:predicate]];

LIKE: It is use in wildcard expression.
CONTAIN: According to your question you should use the contain[cd] because it match the file with search text.
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"fileName CONTAINS[cd] %#",searchDisplayController.searchBar.text];
self.fileArrayAfterPre = [[NSMutableArray alloc] initWithArray:[fileArr filteredArrayUsingPredicate:predicate]];

Related

How to write a nspredicate to get records that contains part of the search term?

How do i write a predicate to filter out data with a search string like this.
Users enters "red pepper".
This should return all the records including, "red pepper", "red bell pepper" etc
This is what i have written.
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(ingredientName contains[c] %#)" ,self.searchIngrediants.text ];
[fetchRequest setPredicate:predicate];
This only returns records that contains the search term such as "red pepper", "belgian red pepper".
Is it possible to do this with a predicate. Im using Objective-c.
Any help would be much appreciated!
For that you need to use LIKE.
NSString *searchStringWithPattern = [self.searchIngrediants.text stringByReplacingOccurrencesOfString:#" " withString:#"*"];
searchStringWithPattern = [NSString stringWithFormat:#"*%#*", searchStringWithPattern];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(ingredientName LIKE[cd] %#)" , searchStringWithPattern];
[fetchRequest setPredicate:predicate];
Objective C Code:-
NSPredicate *predicate;
predicate = [NSPredicate predicateWithFormat:#"ingredientName contains[cd] %#",self.searchIngrediants.text];
Contains will check the character is there or not.
Swift Code :-
var predicate: NSPredicate?
predicate = NSPredicate(format: "ingredientName contains[cd] %#", searchIngrediants.text)
With regular expression it should be something like:
NSString* regex = #"red.*pepper";
NSPredicate* predicate = [NSPredicate predicateWithFormat:#"(ingredientName MATCHES %#)", regex];
If your input has newlines/TABs/... adapt the regex accordingly.

Replace characters from string stored in database by using NSPredicate

I have phone numbers stored in database in the format like +1-541-634-4210 or +1 (541) 634-4210.
I want to search unformatted number like +15416344210 in the database by using NSPredicate but i unable to form the correct predicate format.
I try something like this
NSString *regex = [NSString stringWithFormat:#"+0123456789"];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"number MATCHES %# == %#",regex,phoneNumber]];
So any ideas on how to achieve that?
Any help is much appreciated. Thanks!
Have you tried using predicate.
Swift
let predicate = NSPredicate(format: "SELF MATCHES %#", "[+][0-9]+")
predicate.evaluateWithObject(phone number)
Objective-C
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", "[+][0-9]+"];
[predicate evaluateWithObject:phoneNumber];
Please update the right string based on your conditions.
Try this:
predicate = [NSPredicate predicateWithFormat:#"number MATCHES %#", [[filter componentsSeparatedByString:#"- "] objectAtIndex:0]];

how to find a particular string from a list of strings?

I have to get a particular string from a list of strings using NSPredicate (CoreData). For eg:
if I have the following array from CoreData
Helloworld
helloworld1234
helloworld 12345
from the above list I need only 1 and 3 one as result.
I have tried the following but i get all the three as result
NSPredicate *predicate =[NSPredicate predicateWithFormat:#"contactName CONTAINS [c]%#",[arySeperator objectAtIndex:1]];
NSArray *filteredArray1 = [arrayContacts filteredArrayUsingPredicate:predicate];
Where I am going wrong?
To find all entries that contain the given text as a "whole word", you can use the
predicate "MATCHES" operator, which matches against a regular expression, and the
word boundary pattern \b:
NSString *searchWord = #"Helloworld";
NSString *pattern = [NSString stringWithFormat:#".*\\b%#\\b.*", searchWord];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"contactName MATCHES[c] %#", pattern];
This should also work if you add this predicate to the Core Data fetch request,
instead of filtering an already fetched array of managed objects.
LIKE
The left hand expression equals the right-hand expression: ? and * are allowed as wildcard characters, where ? matches 1 character and * matches 0 or more characters.
NSString *textSearch = #"Raja";
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"firstname LIKE '*%1$#*' OR lastname LIKE '*%1$#*'", textSearch];
You can use below code to get if a string is present in an NSArray:
NSArray* yourArray = [NSArray arrayWithObjects: #"Str1", #"Str2", #"Str3", nil];
if ( [yourArray containsObject: yourStringToFind] ) {
// do found
} else {
// do not found
}

NSPredicate and BeginsWith

I would like to figure out the NSPredicate that will search my Core data for words that begins with:
For example:
description field in the core data has text like this:
My name is Mike
My name is Moe
My name is Peter
My name is George
If I search 'My name is' I need to get the 3 lines
If I search 'My name is M' I need to get the first 2 lines
I tried the code below, but can't get what I need. My guess I need a regular expression, but not sure how to do it.
[NSPredicate predicateWithFormat:#"desc beginswith [cd] %#",word];
I did it this way recently and worked fine. Try it out. I see I don't have [cd] and beginswith but contains. You could give it a try.
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains %#", textField.text];
NSArray *list = [allWords filteredArrayUsingPredicate:predicate];
for(NSString *word in list){
NSLog(#"%#",word);
}
After reading the comments on the starting post:
First of all, you should split up the words in the string from the textfield:
NSArray *myWords = [textField.text componentsSeparatedByString:#" "];
Then doing the same like you first would:
for(NSString *wordFromTextField in myWords){
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains %#", wordFromTextField];
NSArray *list = [allWords filteredArrayUsingPredicate:predicate];
for(NSString *word in list){
NSLog(#"%#",word);
}
}
Instead of NSLogging the words you could add them to an array of course.

NSPredicate contains search in a string that contains number and letters

I have to use NSPredicatefor search through some Core Data objects. But the key nameof the custom object could contains both numbers then letters.
The string could look like:John 1234 Lennonor Ringo Starr.
I normally would use the predicate NSPredicate *predicate = [NSPredicate predicateWithFormat:#"Any name CONTAINS[cd] %#",searchString];
But, if I search for John Lennon the predicate don't return anything, because it can't compare if it contains the characters John Lennon, since is missing the 1234. Any tips what kind of predicate I can use?
You can tokenise your query , maybe as simple as
NSArray *tokens = [querystring componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
Then construct a compound predicate.
NSMutableArray *predarray = [NSMutableArray array];
for(NSString *token in tokens)
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"Any name CONTAINS[cd] %#",token];
[predarray addObject:predicate];
}
NSPredicate *final = [NSCompoundPredicate andPredicateWithSubpredicates:predarray];
And feed that to your query
In real life I would run a bit of validation against each token to check its going to make a valid predicate and wont crash or create a security risk. e.g Strip special chars like "* []"
EDIT:Corrected predicate type to work with questions situation.
Try using LIKE instead of contains, and then you can use wild cards, for instance John*Lennon should match a string that starts with John and ends with Lennon with any number of other characters in between. You can use ? Instead which would match only one character for each question mark if you want more control over what's matched.
You could split the search string up into an array of strings and then switch your predicate to look for any string in the name:
NSArray *strings = [searchString componentsSeparatedByString:#" "];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"ANY %# IN name",strings];

Resources