我有字符串
NSString *str = @"M 2 2 C 5 6 7 8 9 1 2 3M 1 2 C 5 6 7 8 9 1 2 3"
我想要一个像["2 2","5 6 7 8 9 1 2 3","1 2","5 6 7 8 9 1 2 3"]
我想用字典中的类型映射它
["M":"2 2", "C":"5 6 7 8 9 1 2 3"]
我发现可以使用范围属性
获取子字符串NSString *str = @"M 2 2 C 5 6 7 8 9 1 2 3M 1 2 C 5 6 7 8 9 1 2 3"
NSRange r1 = [str rangeOfString:@"M"];
NSRange r2 = [str rangeOfString:@"C"];
NSRange rSub = NSMakeRange(r1.location + r1.length, r2.location - r1.location - r1.length);
NSString *sub = [s substringWithRange:rSub];
但是字母M和C是任意随机的。如何解决整个字符串长度并将其放入数组?
答案 0 :(得分:1)
工作解决方案:
NSString *str = @"M 2 2 C 5 6 7 8 9 1 2 3M 1 2 C 5 6 7 8 9 1 2 3";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"([A-Z])([\\d\\s]*)" options:0 error:nil];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[regex enumerateMatchesInString:str options:0 range:NSMakeRange(0, [str length]) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
NSString *letter = [str substringWithRange:[result rangeAtIndex:1]];
NSString *numbers = [str substringWithRange:[result rangeAtIndex:2]];
NSMutableArray *subArray = dict[letter]?dict[letter]:[[NSMutableArray alloc] init];
[subArray addObject:numbers];
[dict setObject:subArray forKey:letter];
}];
NSLog(@"Dict: %@", dict);
输出:
$>Dict: {
C = (
" 5 6 7 8 9 1 2 3",
" 5 6 7 8 9 1 2 3"
);
M = (
" 2 2 ",
" 1 2 "
);
}
工作原理:
我们使用RegularExpression查找“Letter + anyamountof(任何空格+任意数字)”的组
我们在模式中使用额外的括号来定义“组”
我们列举了匹配项,并且由于我们定义了群组,因此我们可以使用找到的rangeAtIndex:
NSTextCheckingResult
来轻松获取字母和数字。
然后我们将其存储到NSDictionary
。
根据您的需求可以替换什么
删除号码列表之前/之后的空格:
NSString *numbers = [[str substringWithRange:[result rangeAtIndex:2]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
给出了:
$>Dict: {
C = (
"5 6 7 8 9 1 2 3",
"5 6 7 8 9 1 2 3"
);
M = (
"2 2",
"1 2"
);
}
或删除所有空格:
NSString *numbers = [[str substringWithRange:[result rangeAtIndex:2]] stringByReplacingOccurrencesOfString:@" " withString:@""];
给出了:
$>Dict: {
C = (
56789123,
56789123
);
M = (
22,
12
);
}