从服务器获取复杂字符串
@"a:3:{i:0;s:4:\"3530\";i:1;s:4:\"3532\";i:2;s:4:\"4503\";}"
我需要上面字符串中的所有 ID,例如
["3530", "3532", "4503"]
我怎样才能得到上面的输出?我知道一种componentsSeparatedByString
将字符串拆分为数组并得到我的结果的方法。
但我认为这不是一个好方法。所以你能建议我正确的方向RGEX
或等。?
注意:它不是JSON
String 所以我们不能将它转换为Array
Or Dictionary
。
我的逻辑得到了预期的结果。但我不喜欢像下面那样做。
更新:
NSString *temStringValue = @"a:3:{i:0;s:4:\"3530\";i:1;s:4:\"3532\";i:2;s:4:\"4503\";}";
NSArray * arrSplit = [temStringValue componentsSeparatedByString:@"4:\""];
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
if(arrSplit.count > 0 ){
for (NSString *strInner in arrSplit) {
NSArray * arrSplit2 = [strInner componentsSeparatedByString:@"\""];
NSLog(@"%@", arrSplit2);
[finalArray addObject:[arrSplit2 objectAtIndex:0]];
}
}
[finalArray removeObjectAtIndex:0];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:finalArray options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@", jsonString
输出
[
"3530",
"3532",
"4503"
]
所以有人有好主意吗?
这是使用正则表达式的解决方案
该模式搜索后跟一个或多个非双引号字符和第二个双引号的双引号。双引号之间的字符被捕获在一个组中。
NSString* input = @"a:3:{i:0;s:4:\"3530\";i:1;s:4:\"3532\";i:2;s:4:\"4503\";}";
NSString *pattern = @"\"([^\"]+)\"";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
NSArray *matches = [regex matchesInString:input options:0 range:NSMakeRange(0, input.length)];
NSMutableArray *result = [[NSMutableArray alloc] init];
for (NSTextCheckingResult *match in matches) {
[result addObject: [input substringWithRange:[match rangeAtIndex:1]]];
}
NSLog(@"%@", result);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句