美好的一天!
我尝试用这样的格式解析字符串:
{"code":200,"serviceID":"53d22b10e46a5","sender":1,"hasPair":0}
代码:
NSString *strData = [[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
NSRange searchedRange = NSMakeRange(0, [strData length]);
NSLog(@"Data from server = %@", strData);
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\w+)?([0-9])" options:0 error:&error];
NSArray *matches = [regex matchesInString:strData options:0 range: searchedRange];
NSLog(@"The content of arry is%@", matches);
最后NSLog
告诉我下一个
The content of arry is(
"<NSSimpleRegularExpressionCheckingResult: 0x71a9e90>{8, 1}{<NSRegularExpression: 0x71a4370> (w+)?([0-9]) 0x0}",
"<NSSimpleRegularExpressionCheckingResult: 0x71a9d70>{9, 1}{<NSRegularExpression: 0x71a4370> (w+)?([0-9]) 0x0}",
"<NSSimpleRegularExpressionCheckingResult: 0x71a9d90>{10, 1}{<NSRegularExpression: 0x71a4370> (w+)?([0-9]) 0x0}",
"<NSSimpleRegularExpressionCheckingResult: 0x71a9c80>{25, 1}{<NSRegularExpression: 0x71a4370> (w+)?([0-9]) 0x0}",
"<NSSimpleRegularExpressionCheckingResult: 0x71a9ca0>{26, 1}{<NSRegularExpression: 0x71a4370> (w+)?([0-9]) 0x0}",
"<NSSimpleRegularExpressionCheckingResult: 0x71a3460>{28, 1}{<NSRegularExpression: 0x71a4370> (w+)?([0-9]) 0x0}",
"<NSSimpleRegularExpressionCheckingResult: 0x71aa380>{29, 1}{<NSRegularExpression: 0x71a4370> (w+)?([0-9]) 0x0}",
"<NSSimpleRegularExpressionCheckingResult: 0x71aa3a0>{31, 1}{<NSRegularExpression: 0x71a4370> (w+)?([0-9]) 0x0}",
"<NSSimpleRegularExpressionCheckingResult: 0x71a9770>{32, 1}{<NSRegularExpression: 0x71a4370> (w+)?([0-9]) 0x0}",
"<NSSimpleRegularExpressionCheckingResult: 0x71a3440>{34, 1}{<NSRegularExpression: 0x71a4370> (w+)?([0-9]) 0x0}",
"<NSSimpleRegularExpressionCheckingResult: 0x71a9790>{35, 1}{<NSRegularExpression: 0x71a4370> (w+)?([0-9]) 0x0}",
"<NSSimpleRegularExpressionCheckingResult: 0x71aa320>{37, 1}{<NSRegularExpression: 0x71a4370> (w+)?([0-9]) 0x0}",
"<NSSimpleRegularExpressionCheckingResult: 0x71aa340>{49, 1}{<NSRegularExpression: 0x71a4370> (w+)?([0-9]) 0x0}",
"<NSSimpleRegularExpressionCheckingResult: 0x71a8f30>{61, 1}{<NSRegularExpression: 0x71a4370> (w+)?([0-9]) 0x0}"
)
但我想从服务器解析信息并将其保存到数组中。拜托,告诉我我的错误。 谢谢!
答案 0 :(得分:1)
您的输入字符串看起来像JSON,因此使用NSJSONSerialization
比使用正则表达式更有效:
NSString *json = @"{\"code\":200,\"serviceID\":\"53d22b10e46a5\",\"sender\":1,\"hasPair\":0}";
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
id obj = [NSJSONSerialization JSONObjectWithData:jsonData
options:0
error:&error];
if (obj) {
NSAssert([obj isKindOfClass:[NSDictionary class]], @"Expected a dictionary");
NSDictonary *dictObj = (NSDictionary *)obj;
NSNumber *code = dictObj[@"code"];
NSString *serviceId = dictObj[@"serviceID"];
NSNumber *sender = dictObj[@"sender"];
NSNumber *hasPair = dictObj[@"hasPair"];
} else {
NSLog(@"Failed to parse JSON: %@", [error localizedDescription]);
}