开发者

Extract values between parenthesis from NSString

开发者 https://www.devze.com 2022-12-25 11:48 出处:网络
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开发者_如何学C. I managed to extract the

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开发者_如何学C. I managed to extract the x using a NSScanner but I haven't figured out the proper way to extract out the y.


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


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.


Scan up to the ‘(’, then scan it, then scan up to the ')'. The result of the last scan is yyyy.


you might have a look at PKTokenizer in ParseKit:

http://parsekit.com

0

精彩评论

暂无评论...
验证码 换一张
取 消