Trim 基于字符出现次数的 NSString

Trim an NSString Based Upon Number Of Character Occurrences

我在检测到 3 个换行实例后尝试 trim NSString。 (\n)。所以,这就是我尝试过的:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\n" options:NSRegularExpressionCaseInsensitive error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, [myString length])];

现在,匹配的数量总是超过 3,我想在字符串到达​​第三个 \n 时立即停止。有谁知道这样做有什么好的逻辑吗?

如果 3 个换行实例总是组合在一起,那就很简单了:

NSString *testString = @"The quick brown fox jumps \n\n\n over the lazy dog. \n\n\n New Line.";
[[string componentsSeparatedByString:@"\n\n\n"] firstObject]

否则你可以使用:

        NSError *error;
        NSString *pattern = @"(\A|\n\s*\n\s*\n)(.*?\S[\s\S]*?\S)(?=(\Z|\s*\n\s*\n\s*\n))";
        NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:pattern
                                                                          options:NSRegularExpressionCaseInsensitive
                                                                            error:&error];
        [regex enumerateMatchesInString:testString
                                options:0
                                  range:NSMakeRange(0, [testString length])
                             usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
                                 NSString *match = [testString substringWithRange:[result rangeAtIndex:2]];
                                 NSLog(@"match = '%@'", match);
                             }];

(摘自 this 回答)

NSString* originalString = @"This\nis\na\ntest string";
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@".*\n.*\n.*\n" options:0 error:nil];
NSRange range = [regex rangeOfFirstMatchInString:originalString options:0 range:(NSRange){0,originalString.length}];
NSString* trimmedString = [originalString substringFromIndex:range.length];

NSLog(@"Original: %@", originalString);
NSLog(@"Trimmed: %@", trimmedString);

打印:

2015-02-05 21:39:41.491 TestProject[4258:1269568] Original: This
is
a
test string
2015-02-05 21:39:41.492 TestProject[4258:1269568] Trimmed: test string