給定格式字符串 @"( 1, 2, 3, 4)" 或 @"(\n 1,\n 2,\n 3,\n 4\n)",需提取其中的數字並轉換為 NSArray 或 NSMutableArray。
NSString *numberVector = @"(\n 1,\n 2,\n 3,\n 4\n)";
// 1. 使用正則表達式移除所有非數字、非逗號字符
// 模式 [^0-9,] 表示「非 0-9 和非逗號」的字符
NSString *onlyNumbers = [numberVector stringByReplacingOccurrencesOfString:@"[^0-9,]"
withString:@""
options:NSRegularExpressionSearch
range:NSMakeRange(0, [numberVector length])];
// 結果:"1,2,3,4"
// 2. 按逗號分割為數組
NSArray *numbers = [onlyNumbers componentsSeparatedByString:@","];
// 結果:@[@"1", @"2", @"3", @"4"]
// 3. 可選:轉換為整型數組
NSMutableArray *intNumbers = [NSMutableArray array];
for (NSString *str in numbers) {
[intNumbers addObject:@([str integerValue])];
}
// 結果:@[@1, @2, @3, @4]
| 模式 | 含義 |
|---|---|
[^0-9,] | 字符集取反:匹配任意非數字、非逗號的單個字符(包括括號、空格、換行符等) |
NSRegularExpressionSearch | 指定使用 ICU 正則引擎解析模式 |
NSString *numberVector = @"( 1, 2, 3, 4)";
NSScanner *scanner = [NSScanner scannerWithString:numberVector];
NSMutableArray *numbers = [NSMutableArray array];
NSCharacterSet *digits = [NSCharacterSet decimalDigitCharacterSet];
while (!scanner.isAtEnd) {
// 跳過非數字字符
[scanner scanCharactersFromSet:[digits invertedSet] intoString:NULL];
// 掃描數字
NSString *numberStr;
if ([scanner scanCharactersFromSet:digits intoString:&numberStr]) {
[numbers addObject:@([numberStr integerValue])];
}
}
// 結果:@[@1, @2, @3, @4]
優勢:無正則編譯開銷、原生 C 級別實現、處理超長字符串更高效。
// 正則匹配數字模式(含負號、小數點、指數)
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?"
options:0 error:NULL];
NSArray *matches = [regex matchesInString:numberVector options:0 range:NSMakeRange(0, numberVector.length)];
NSMutableArray *numbers = [NSMutableArray array];
for (NSTextCheckingResult *match in matches) {
NSString *numStr = [numberVector substringWithRange:match.range];
[numbers addObject:@([numStr doubleValue])];
}