NSTextfield and user inputted regex - objective-c

Is there an easy way to take a user inputted NSString from an NSTextfield, and convert it to a valid objc regex?
I would like to escape all the '\' characters, but obviously not all the unneeded ones, i.e.... '\n', ' \xA9', '\r' etc....
for example this:
NSString *rejectString = #"^Steve\-Smi+.*+(\n)?"
needs to become this:
#"^Steve\\-Smi+.*+(\n)?"

I have ended up using NSPredicate instead, its much more user friendly:
NSArray *array = [NSArray arrayWithObjects: ojb1, obj2, obj3, obj4, nil];
NSMutableArray *filteredArray = [NSMutableArray new];
NSString *ignoreString = [ignoreStringTextfield stringValue];
for (NSString *name in array)
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"NOT (SELF MATCHES %#)", ignoreString];
if ([predicate evaluateWithObject:name])
[filteredArray addObject:name];
}
return filteredArray;

Related

Using NSPredicate to filter an NSMutableArray of NSDictionaries to find if a "key" exists

I have an NSMutableArray of dictionaries. I am using NSPredicate to filter through the array to find if a dictionary with a particular key exists or not.
I have referred to various examples, one of the closest is here: Using NSPredicate to filter an NSArray based on NSDictionary keys. However, I don't wish to have a value to the key. My problem is that I want to find the key first. I tried different syntaxes, but it did not help.
What I have done so far:
NSString *key = #"open_house_updated_endhour";
NSPredicate *predicateString = [NSPredicate predicateWithFormat:#"%K", key];
//NSPredicate *predicateString = [NSPredicate predicateWithFormat:#"%K contains [cd]", key]; Doesn't work.
//NSPredicate *predicateString = [NSPredicate predicateWithFormat:#"%K == %#", key]; Won't work because it expects a value here.
NSLog(#"predicate %#",predicateString);
NSArray *filtered = [updatedDateAndTime filteredArrayUsingPredicate:predicate]; // updatedDateAndTime is the NSMutableArray
A dictionary delivers nil as value for absent key. So simply compare the key against nil.
NSPredicate *predicateString = [NSPredicate predicateWithFormat:#"%K==NULL", key]; // Dictionaries not having the key
NSPredicate *predicateString = [NSPredicate predicateWithFormat:#"%K!=NULL", key]; // Dictionaries having the key
Try it:
NSArray *Myarray = [NSArray arrayWithObject:[NSMutableDictionary dictionaryWithObject:#"my hello string" forKey:#"name"]];
NSArray *filteredarray = [Myarray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(name == %#)", #"my hello string"]];
NSLog("%#",filteredarray);
Another example :
NSString *mycategory = #"iamsomeone";
NSArray *myitems = #[#{ #"types" : #[#"novel", #"iamsomeone", #"dog"] },
#{ #"types" : #[#"cow", #"iamsomeone-iam", #"dog"] },
#{ #"types" : #[#"cow", #"bow", #"cat"] }];
NSPredicate *mypredicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
NSArray *categories = [evaluatedObject objectForKey:#"types"];
return [categories containsObject:mycategory];
}];
NSArray *outpuArray = [myitems filteredArrayUsingPredicate:mypredicate];
NSLog(#"hello output:%#",outpuArray);

Search through NSArray of objects with different locale

I have an array of phone number objects, the phone number model is as follows:
#property NSString *hotlineName;
#property NSString *hotlineNameAr;
#property NSString *hotlineNumber;
#property NSString *hotlineImage;
#property NSInteger hotlineID;
#property RLMArray<Tags> *hotlineTags;
when I perform a search, I filter the array if either hotlineName, hotlineNameAr, hotlineNumber and in property hotlineTags: tagName and tagNameAr contain the search text.
I used NSPredicate to filter the array as such:
-(void) searchForText: (NSString *) searchText{
NSString *predicateFormat = #"SELF.%K contains[cd] %#";
NSString *tagFormat = #"ANY SELF.hotlineTags.%K contains[cd] %#";
NSString *searchNameAttribute = #"hotlineName" ;
NSString *searchTagAttribute = #"tagName";
NSString *searchNameAttribute_ar = #"hotlineNameAr" ;
NSString *searchTagAttribute_ar = #"tagNameAr";
NSString *numberAttribute = #"hotlineNumber";
NSPredicate *namePredicate = [NSPredicate predicateWithFormat:predicateFormat, searchNameAttribute, searchText];
NSPredicate *tagPredicate = [NSPredicate predicateWithFormat:tagFormat, searchTagAttribute, searchText];
NSPredicate *namePredicate_ar = [NSPredicate predicateWithFormat:predicateFormat, searchNameAttribute_ar, searchText];
NSPredicate *tagPredicate_ar = [NSPredicate predicateWithFormat:tagFormat, searchTagAttribute_ar, searchText];
NSPredicate *numberPredicate = [NSPredicate predicateWithFormat:predicateFormat, numberAttribute, searchText];
NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:#[namePredicate, numberPredicate, tagPredicate, namePredicate_ar, tagPredicate_ar]];
filteredResults = [hotlines_arr filteredArrayUsingPredicate:predicate];
}
and so far it works well, the problem arose when I search with numbers in a different locale, in this instance in Arabic, so used I NSNumberFormatter as such:
// Convert string From Arabic/Persian numbers to English numbers
+(NSString *) convertToEnglishNumber:(NSString *) string {
// NSNumericSearch
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSLocale *locale = [NSLocale localeWithLocaleIdentifier:#"EN"];
[formatter setLocale:locale];
NSNumber *number = [formatter numberFromString:string];
return [number stringValue];
}
but the problem with NSNumberFormatter is that any leading zero's are ignored in the conversion, so I need an alternative to format the NSString based on locale or search array while taking in consideration locale, the same option in spotlight search.
I also tried formatting as such but it was in vain.
NSString *str = [[NSString alloc] initWithFormat:#"%#" locale:locale, searchText];
NSString *localizedString =[NSString localizedStringWithFormat:#"%#", searchText];
As I couldn't think of any other option and this was a last resort, I ended up replacing the string but I'm very unhappy with answer:
+ (NSString *) replaceStrings: (NSString *) textToEdit{
NSLocale *locale = [NSLocale localeWithLocaleIdentifier:#"ar"];
for (NSInteger i= 0; i < 10; i++) {
NSString *stringVal = [#(i) stringValue];
NSString *localeString = [#(i) descriptionWithLocale:locale];
textToEdit = [textToEdit stringByReplacingOccurrencesOfString:localeString withString:stringVal];
}
return textToEdit;
}

Searching NSArray using suffixes

I have a word list stored in an NSArray, I want to find all the words in it with the ending 'ing'.
Could someone please provide me with some sample/pseudo code.
Use NSPredicate to filter NSArrays.
NSArray *array = #[#"test", #"testing", #"check", #"checking"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF ENDSWITH 'ing'"];
NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];
Let's say you have an array defined:
NSArray *wordList = // you have the contents defined properly
Then you can enumerate the array using a block
// This array will hold the results.
NSMutableArray *resultArray = [NSMutableArray new];
// Enumerate the wordlist with a block
[wordlist enumerateObjectsUsingBlock:(id obj, NSUInteger idx, BOOL *stop) {
if ([obj hasSuffix:#"ing"]) {
// Add the word to the result list
[result addObject:obj];
}
}];
// resultArray now has the words ending in "ing"
(I am using ARC in this code block)
I am giving an example using blocks because its gives you more options should you need them, and it's a more modern approach to enumerating collections. You could also do this with a concurrent enumeration and get some performance benefits as well.
Just loop through it and check the suffixes like that:
for (NSString *myString in myArray) {
if ([myString hasSuffix:#"ing"]){
// do something with myString which ends with "ing"
}
}
NSMutableArray *results = [[NSMutableArray alloc] init];
// assuming your array of words is called array:
for (int i = 0; i < [array count]; i++)
{
NSString *word = [array objectAtIndex: i];
if ([word hasSuffix: #"ing"])
[results addObject: word];
}
// do some processing
[results release]; // if you're not using ARC yet.
Typed from scratch, should work :)

Filter an NSArray which contains custom objects

I have UISearchBar, UITableView, a web service which returns a NSMutableArray that contain objects like this:
//Food.h
Food : NSObject {
NSString *foodName;
int idFood;
}
#property (nonatomic, strong) NSString *foodName;
And the array:
Food *food1 = [Food alloc]initWithName:#"samsar" andId:#"1"];
Food *food2 = [Food alloc] initWithName:#"rusaramar" andId:#"2"];
NSSarray *array = [NSArray arrayWithObjects:food1, food2, nil];
How do I filter my array with objects with name beginning with "sa"?
You can filter any array like you'd like to with the following code:
NSMutableArray *array = ...;
[array filterUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
return [evaluatedObject.foodName hasPrefix:searchBar.text];
}];
This will filter the array "in-place" and is only accessible on an NSMutableArray. If you'd like to get a new array that's been filtered for you, use the filteredArrayUsingPredicate: NSArray method.
NSString *predString = [NSString stringWithFormat:#"(foodName BEGINSWITH[cd] '%#')", #"sa"];
NSPredicate *pred = [NSPredicate predicateWithFormat:predString];
NSArray *array = [arr filteredArrayUsingPredicate:pred];
NSLog(#"%#", array);

NSDictionary - List all

In a NSMutableDictionary like this:
[NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithString:firstName], #"NAME",
[NSNumber numberWithFloat:familyName], #"SURNAME",
nil];
How can all of its elements be converted to the NSString? with the requirement that names and surnames are arranged in string like this: "name, surname, name, surname..."?
This gives a string with all the names but not surnames:
NSString * result = [[urlArray valueForKey:#"NAME"] componentsJoinedByString:#", "];
Is there a way similar to the one above to create a string with all the values of NSMutableDictionary?
Try something like this:
NSString *result = [NSString stringWithFormat:#"%#, %#", [urlArray valueForKey:#"SURNAME"], [urlArray valueForKey:#"NAME"]];
The %# represents an objective-c object for more details see the Apple docs
The code to make a NSString from an NSDictionary may look like (if you're trying to print out everything in the NSDictionary)
NSMutableString* mutableString = [NSMutableString string];
NSDictionary* dictionary;
for(NSString* key in [dictionary allKeys])
{
[mutableString appendString:[[dictionary objectForKey:key] description]];
}