1

我有一个 NSString ,当 NSlogged 返回这个时:

device status: (SOME LETTERS), session code: (SOME NUMBERS)

如何从初始字符串中提取这两个而不实际切割字符串以具有类似的内容:

NSString* str1 = text for "device status";
NSString* str1 = text for "session code";
4

3 回答 3

3

简单的代码会像。

因为您可以使用componentsSeparatedByString

- (NSArray *)componentsSeparatedByString:(NSString *)separator

表示返回一个数组,其中包含来自接收者的子字符串,这些子字符串已被给定的分隔符分割。

NSString *string = @"device status: (SOME LETTERS), session code: (SOME NUMBERS)";
NSArray *array = [string componentsSeparatedByString:@","];
NSArray *one = [[array objectAtIndex:0] componentsSeparatedByString:@":"];
NSArray *two = [[array objectAtIndex:1] componentsSeparatedByString:@":"];

NSLog(@"key = %@ and Value = %@",[one objectAtIndex:0],[one objectAtIndex:1]);
NSLog(@"key = %@ and Value = %@",[two objectAtIndex:0],[two objectAtIndex:1]); 
于 2013-10-18T13:17:07.770 回答
2

NSRegularExpression交朋友:

NSString* str = @"device status: dead, session code: 666";

NSError *err;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"device status: (//w*), session code: (//d*)" options:0 error:&err];
if (err) {
    NSLog(@"Returned an error: %@", [err localizedDescription]);
}
NSArray* matches = [regex matchesInString:str options:0 range:NSMakeRange(0, [str length])];
//  get the first match
NSTextCheckingResult *match = matches[0];

// extract the groups
NSString *deviceStatus = [str substringWithRange:[match rangeAtIndex:1]];
NSString *sessionCode = [str substringWithRange:[match rangeAtIndex:2]];
于 2013-10-18T13:19:58.107 回答
0
NSArray *commaSeparated = [originalString componentsSeparatedByString:@", "];
NSArray *colonSeparated1 = [commaSeparated[0] componentsSeparatedByString:@": ";
NSArray *colonSeparated2 = [commaSeparated[1] componentsSeparatedByString:@": ";
NSString *statusString = colonSeparated1[1];
NSString *sessionString = colonSeparated2[1];
于 2013-10-18T13:17:55.070 回答