find a letter anywhere in an array of strings ios - ios

I have the method below for filtering some results:
Currently it does this:
array: alpha, apple, aries, bravo
type a:
alpha
apple
aries
type l (now al)
alpha
I wanted to do this:
new search:
type p=
alPha
apple
below is the code
thank you kindly in advance
-(void) filterResults:(NSString *)searchText{
NSMutableArray *test = [NSMutableArray arrayWithArray:self.listContent];
[self.filteredListContent removeAllObjects]; // First clear the filtered array.
for (int i=0; i<[test count]; i++) {
NSString *stringResult = [test objectAtIndex:i];
NSComparisonResult result = [stringResult compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame){
[self.filteredListContent addObject:stringResult];
}
}
[self.filteredListContent sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)];//sort alphabetically
NSLog(#"filtered results = %#",self.filteredListContent);
}

To find the letter anywhere in your string, replace this:
NSComparisonResult result = [stringResult compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame){
[self.filteredListContent addObject:stringResult];
}
with this:
NSRange range = [stringResult rangeOfString:searchText];
if (range.location != NSNotFound) {
[self.filteredListContent addObject:stringResult];
}
Note that it will have to find all of the characters, in order.
If you want to find any of the characters, then use rangeOfCharacterFromSet:.

Try this one.
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"SELF beginswith '%#'", searchText]];
self.filteredListContent = [self.listContent filteredArrayUsingPredicate:predicate];
Hope this helps you.

Related

Regexp matching group not working on objective-c

I'm trying to get from this string: 5556007503140005
Two strings. "555600750314" and "0005"
I'm Using the regexp ^([a-z0-9]*)([0-9]{4})$that works fine on the regexp tools, but when i use this on my code I only get 1 match.
this is the code
-(NSDictionary *)parse_barcode:(NSString *)barcode {
NSString *regexp = #"^([a-z0-9]*)([0-9]{4})$";
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",regexp];
if ([predicate evaluateWithObject:barcode]) {
NSError *error;
NSRegularExpression *regular_exp = [NSRegularExpression regularExpressionWithPattern:regexp options:0 error:&error];
NSArray *matches = [regular_exp matchesInString:barcode options:0 range:NSMakeRange(0, [barcode length])];
for (NSTextCheckingResult *match in matches) {
NSLog(#"match %# :%#",[barcode substringWithRange:[match range]], match);
}
}
return nil;
}
But the match is always the entire string (Barcode)
You get the right match, you are just not printing them correctly. You need to use numberOfRanges to get the individual groups (i.e. sections enclosed in parentheses), and then call rangeAtIndex: for each group, like this:
for (NSTextCheckingResult *match in matches) {
for (int i = 0 ; i != match.numberOfRanges ; i++) {
NSLog(#"match %d - %# :%#", i, [barcode substringWithRange:[match rangeAtIndex:i]], match);
}
}

Create Regular Expression for specified string in objective c

My NSString like below
#"[o=uid=35=] hghk\u00c2\u00a0 [o=uid=30=] [o=uid=35=] cong."
I need to create regular expression which search numeric values (e.g in first square brackets there is 35 in second there is 30 like this) in between square parenthesis. How could i achieve this task. Is there any alternate way to search numeric values in between square parenthesis? Please help me to short resolve from this. your help would be appreciable.
Using NSRegularExpression,
NSString* strSource = #"[o=uid=35=] hghk\u00c2\u00a0 [o=uid=30=] [o=uid=35=] cong.";
NSError* errRegex = NULL;
NSRegularExpression* regex = [NSRegularExpression
regularExpressionWithPattern:#"uid=([0-9]+)"
options:NSRegularExpressionCaseInsensitive
error:&errRegex];
NSUInteger countMatches = [regex numberOfMatchesInString:strSource
options:0
range:NSMakeRange(0, [strSource length])];
NSLog(#"Number of Matches: %ld", (unsigned long)countMatches);
[regex enumerateMatchesInString:strSource options:0
range:NSMakeRange(0, [strSource length])
usingBlock:^(NSTextCheckingResult* match,
NSMatchingFlags flags, BOOL* stop) {
NSLog(#"Ranges: %ld", (unsigned long)[match numberOfRanges]);
NSString *matchFull = [strSource substringWithRange:[match range]];
NSLog(#"Match: %#", matchFull);
for (int i = 0; i < [match numberOfRanges]; i++) {
NSLog(#"\tRange %i: %#", i,
[strSource substringWithRange:[match rangeAtIndex:i]]);
}
}];
if (errRegex) {
NSLog(#"%#", errRegex);
}
http://regexpal.com/
use above link to check the expression
\b[0-9]+
to find all the integer values
([0-9])+
it works.
You can build a regular expression like this:
uid=([0-9]+)
This will find any numbers after "uid=" sequence in a string. The value of the number will be available in "match 1", since it is put in parentheses. You can try out this Regex interactively with http://rubular.com/.
if you just want numeric value then you can try this
NSString *mainString = #"[o=uid=35=] hghk\u00c2\u00a0 [o=uid=30=] [o=uid=35=] cong.";
NSArray *arr = [mainString componentsSeparatedByString:#"="];
for(int i=0;i<arr.count;i++)
{
NSString *newString = arr[i];
NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([newString rangeOfCharacterFromSet:notDigits].location == NSNotFound)
{
NSLog(#"%#",newString);
// newString consists only of the digits 0 through 9
}
}
Here is my code,it works perfectly..we can check easily below array contains object(numbers between '[' and ']') or not without using any regex.
NSString *tmpTxt = #"[o=uid=35=] hghk\u00c2\u00a0 [o=uid=30=] [o=uid=35=] cong.";
NSString*splittxt=tmpTxt;
NSMutableArray*array=[[NSMutableArray alloc]init];
for (int i=0; i<i+1; i++) {
NSRange r1 = [splittxt rangeOfString:#"["];
NSRange r2 = [splittxt rangeOfString:#"]"];
NSRange rsub=NSMakeRange(r1.location + r1.length-1, r2.location - r1.location - r1.length+2);
if (rsub.length >2 ){
NSCharacterSet *AllowedChars = [[NSCharacterSet characterSetWithCharactersInString:#"1234567890"] invertedSet];
NSString*stringg=[splittxt substringWithRange:rsub];
stringg = [[stringg componentsSeparatedByCharactersInSet:AllowedChars] componentsJoinedByString:#""];
[array addObject:stringg];
}
else
{
break;
}
splittxt=[splittxt stringByReplacingCharactersInRange:rsub withString:#""];
}
NSLog(#"%#",array);
}
the array value is
(
35,
30,
35
)

Search display controller iOS results disappear then reappear between words

I am searching my products like the below. It works fine however when searching between 2 words the results disappear then reappear once the user has entered the first character of the next word. i.e if I search "td pro" or "pro td" the results are there. If I search like this td(i have a result) td(space) I have NO result td p(I have a result) just to add I need to separate the words by space in componentsSeperatedByString because the user may not search for a product in any particular order. Unless there is a better method?
Here is my code:
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
[self.filteredListContent removeAllObjects]; // First clear the filtered array.
for (XMLStringFile *new in rssOutputData_MutableArray)
{
//Product scope
if ([scope isEqualToString:#"Product"])
{
// Split into search text into separate "words"
NSArray * searchComponents = [searchText componentsSeparatedByString: #" "];
;
BOOL foundSearchText = YES;
// Check each word to see if it was found
for (NSString * searchComponent in searchComponents) {
NSRange result = [new.xmlItem rangeOfString:searchComponent options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)];
NSRange descriptionRange = [new.xmlDescription rangeOfString:searchComponent options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)];
foundSearchText &= (result.location != NSNotFound|| descriptionRange.location != NSNotFound);
}
// If all search words found, add to the array
if (foundSearchText)
{
[self.filteredListContent addObject: new];
}
}
}
}
Many thanks
I fixed it with the help of another stack question that someone helped me with.
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
[self.filteredListContent removeAllObjects]; // First clear the filtered array.
for (XMLStringFile *new in rssOutputData_MutableArray)
{
//Product scope
if ([scope isEqualToString:#"Product"])
{
// Split into search text into separate "words"
NSArray * searchComponents = [searchText componentsSeparatedByString: #" "];
//Before searching trim off the whitespace
searchText = [searchText stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
BOOL foundSearchText = YES;
// Check each word to see if it was found
for (NSString * searchComponent in searchComponents) {
NSRange result = [new.xmlItem rangeOfString:searchComponent options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)];
NSRange descriptionRange = [new.xmlDescription rangeOfString:searchComponent options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)];
foundSearchText &= (result.location != NSNotFound|| descriptionRange.location != NSNotFound);
}
// If all search words found, add to the array
if (foundSearchText)
{
[self.filteredListContent addObject: new];
}
}
}
}
The winning line is:
//Before searching trim off the whitespace
searchText = [searchText stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];

ios how to extract all rangeOfString of an array in a for loop?

I want to extract all "daughter" of a NSarray.
For example, nsarray is made like this:
hello
hi
hello daughter
my goodness
daughter (someone)
my daughter
how are you?
etc.
And I want to extract all lines that contain "daughter". Could you point me in right direction?
My current code is:
for (NSString *mystring in self.array)
{
if ([mystring rangeOfString:searchText].location!=NSNotFound)
{
NSUInteger idx = [self.array indexOfObject:mystring];
[self.filterarray addObject: mystring];
}
}
NSArray *lines = ...;
NSArray *filteredLines = [lines filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSString *string, NSDictionary *bindings) {
return ([string rangeOfString:searchText].location != NSNotFound);
}]];
(requires iOS 4.0 or later)
If you need to support earlier system versions use this:
NSArray *lines = ...;
NSArray *filteredLines = [lines filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(SELF contains[c] %#)", searchText]];
(requires iOS 3.0 or later)
NSString *textViewText = #“hello hi hello daughter my goodness daughter (someone) my daughter how are you? etc.”;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:textViewText];
NSArray *highlightWords = #[#“daughter”,#”hello”];
for(NSString *word in highlightWords)
{
NSRange range = NSMakeRange(0, textViewText.length);
do{
range = [textViewText rangeOfString:word options:NSCaseInsensitiveSearch range:range];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
if (range.location != NSNotFound)
range = NSMakeRange(range.location + 1, textViewText.length - (range.location + 1));
}while(range.location != NSNotFound);
}

UIScope Bar doesn't show items (if no Searchtext is submitted)

i have a Searchbar with a Scopebar in my RootViewController. If I am searching for the items it's working very fine, also if I searching in a Scope Range. But how is it possible to show Scope Results, if no Searchtext was given from the User?
A Code Sample would be very fine.
Here is the Code which filter after the User set Text into the Seachbar.
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
[self.filteredContent removeAllObjects]; // First clear the filtered array.
for (test *new in tabelle)
{
//cat1
if ([scope isEqualToString:#"cat1"] && [new.Location isEqualToString:#"cat1"])
{
NSComparisonResult result = [new.TText compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame)
{
[self.filteredContent addObject:new];
}
}
//cat2
if ([scope isEqualToString:#"cat2"] && [new.Location isEqualToString:#"cat2"])
{
NSComparisonResult result = [new.TText compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame)
{
[self.filteredContent addObject:new];
}
}
//all
if ([scope isEqualToString:#"Alle"])
{
NSComparisonResult result = [new.TText compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame)
{
[self.filteredContent addObject:new];
}
}
}
}
I want results without any typed letter in the Searchbar
Like this image but without the typed in letter: http://edumobile.org/iphone/wp-content/uploads/2010/03/search.jpg

Resources