我有一个NSString,当NSlogged返回时:
device status: (SOME LETTERS), session code: (SOME NUMBERS)
如何从初始字符串中提取两个字符串,而不实际切割字符串,如下所示:
NSString* str1 = text for "device status";
NSString* str1 = text for "session code";
答案 0 :(得分: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]);
答案 1 :(得分: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]];
答案 2 :(得分:0)
NSArray *commaSeparated = [originalString componentsSeparatedByString:@", "];
NSArray *colonSeparated1 = [commaSeparated[0] componentsSeparatedByString:@": ";
NSArray *colonSeparated2 = [commaSeparated[1] componentsSeparatedByString:@": ";
NSString *statusString = colonSeparated1[1];
NSString *sessionString = colonSeparated2[1];