Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract values between parenthesis from NSString

I have an NSString that will be something like "xxxx (yyyyy)" where x and y can be any character. I'd like to extract just the y from inside the parenthesis. I managed to extract the x using a NSScanner but I haven't figured out the proper way to extract out the y.

like image 934
Ternary Avatar asked Mar 28 '10 23:03

Ternary


2 Answers

Just to be complete:

If you are absolutely sure of the format of your output you can use the array methods:

NSString *inputString; // this is in the form "xxxx(yyyy)"

NSCharacterSet *delimiters = [NSCharacterSet characterSetWithCharactersInString:@"()"];
NSArray *splitString = [inputString componentsSeparatedByCharactersInSet:delimiters];

NSString *xString = [splitString objectAtIndex:0];
NSString *yString = [splitString objectAtIndex:1];

Of course, you need to be sure that the delimiting characters don’t exist in the inputString

like image 79
Abizern Avatar answered Oct 20 '22 20:10

Abizern


Easiest way would be to use RegExKit:

http://regexkit.sourceforge.net/

Then you'd do something like:

[@"xxxx(yyyyy)" getCapturesWithRegexAndReferences:@"\\((.*)\\)",@"$1", &extractedString,nil];

and extractedString would contain whatever was in parenthesis.

like image 35
wadesworld Avatar answered Oct 20 '22 21:10

wadesworld