2015-02-05 62 views
0

我試圖在檢測到3個新行實例後修剪NSString。 (\ n)的。所以,這就是我已經試過:根據字符出現次數修剪NSString

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

現在,比賽的數量始終超過3,我想正確的,因爲它擊中第三\ n停止的字符串。有沒有人知道有什麼好的邏輯來做到這一點?

回答

1

如果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回答)

0
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