Split line after: and before?

I have a long line like this:

je!tress:e?tu!tress:es?il!tress:e?nous!tress:ons?vous!tress:ez?ils!tress:ent? 

I want to split the line after: and earlier ?, so I want to have in the array:

 {e,es,e,ons,ez,en} 

I know I can do this:

  NSArray *subStrings = [stringToChange componentsSeparatedByString:@":"]; 

but this is not enough. How can I do this, please? Any help would be appreciated!

+7
ios objective-c nsstring
source share
4 answers

Another option might be to use the NSRegularExpression class.

Using this template:

 \\:([^\?]+)\? 

Code example:

 NSString *sample = @"je!tress:e?tu!tress:es?il!tress:e?nous!tress:ons?vous!tress:ez?ils!tress:ent?"; NSString *pattern = @"\\:([^\?]+)\?"; NSError *error = NULL; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error]; NSArray *matches = [regex matchesInString:sample options:0 range:NSMakeRange(0, [sample length])]; if(!error && [matches count] > 0) { for (NSTextCheckingResult *match in matches) { NSRange matchRange = [match range]; NSLog(@"%@" ,[sample substringWithRange:matchRange]); } } 

Output:

 2015-07-03 12:16:39.037 TestRegex[3479:48301] :e 2015-07-03 12:16:39.039 TestRegex[3479:48301] :es 2015-07-03 12:16:39.039 TestRegex[3479:48301] :e 2015-07-03 12:16:39.040 TestRegex[3479:48301] :ons 2015-07-03 12:16:39.040 TestRegex[3479:48301] :ez 2015-07-03 12:16:39.040 TestRegex[3479:48301] :ent 
+2
source share

Use NSScanner to parse a string, search for tags : and ? . You can discard text that you don't need and grab the parts you make (based on which tag you find) and add them to the array.

+1
source share

try it,

  NSString *names = @"je!tress:e?tu!tress:es?il!tress:e?nous!tress:ons?vous!tress:ez?ils!tress:ent?"; 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); 
+1
source share

To be simpler, you can try the following code:

 NSString *string = @"je!tress:e?tu!tress:es?il!tress:e?nous!tress:ons?vous!tress:ez?ils!tress:ent?"; NSArray *firstArray = [string componentsSeparatedByString:@":"]; NSMutableArray *finalArray = [[NSMutableArray alloc] init]; for (NSString *newString in firstArray) { NSArray *tempArray = [newString componentsSeparatedByString:@"?"]; if ([tempArray count] > 1) { [finalArray addObject:[tempArray firstObject]]; } } NSLog(@"%@",finalArray); 
+1
source share

All Articles