Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex in objective C

I want to extract only the names from the following string

bob!33@localhost @clement!17@localhost jack!03@localhost

and create an array [@"bob", @"clement", @"jack"].

I have tried NSString's componentsseparatedbystring: but it didn't work as expected. So I am planning to go for regEx.

  1. How can I extract strings between ranges and add it to an array using regEx in objective C?
  2. The initial string might contain more than 500 names, would it be a performance issue if I manipulate the string using regEx?
like image 891
Clement Prem Avatar asked Dec 01 '22 17:12

Clement Prem


2 Answers

You can do it without regex as below (Assuming ! sign have uniform pattern in your all words),

NSString *names = @"bob!33@localhost @clement!17@localhost jack!03@localhost";
NSArray *namesarray = [names componentsSeparatedByString:@" "];
NSMutableArray *desiredArray = [[NSMutableArray alloc] initWithCapacity:0];
[namesarray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSRange rangeofsign = [(NSString*)obj rangeOfString:@"!"];
    NSString *extractedName = [(NSString*)obj substringToIndex:rangeofsign.location];
    [desiredArray addObject:extractedName];
}];
NSLog(@"%@",desiredArray);

output of above NSLog would be

(
    bob,
    "@clement",
    jack
)

If you still want to get rid of @ symbol in above string you can always replace special characters in any string, for that check this

If you need further help, you can always leave comment

like image 120
Janak Nirmal Avatar answered Dec 20 '22 15:12

Janak Nirmal


NSMutableArray* nameArray = [[NSMutableArray alloc] init];
NSArray* youarArray = [yourString componentsSeparatedByString:@" "];
for(NSString * nString in youarArray) {
   NSArray* splitObj = [nString componentsSeparatedByString:@"!"];
   [nameArray addObject:[splitObj[0]]];
}    
NSLog(@"%@", nameArray);
like image 38
Retro Avatar answered Dec 20 '22 15:12

Retro