Henry F
Henry F

Reputation: 4980

Trim an NSString Based Upon Number Of Character Occurrences

I'm trying to trim an NSString after I detect 3 new line instances. (\n). So, this is what I've tried:

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

Now, number of matches will always exceed 3, and I want to stop the string right as it hits the third \n. Does any one know any good logic to do this?

Upvotes: 0

Views: 173

Answers (2)

erkanyildiz
erkanyildiz

Reputation: 13214

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);

Prints:

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

Upvotes: 0

psobko
psobko

Reputation: 1568

If the 3 new line instances are always grouped together it's pretty easy:

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]

Otherwise you could use:

        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);
                             }];

(Taken from this answer)

Upvotes: 1

Related Questions